babylon.viewer.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268
  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) {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};
  83. 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)}}();
  84. (function universalModuleDefinition(root, factory) {
  85. var amdDependencies = [];
  86. var CANNON = root.CANNON || this.CANNON;
  87. var OIMO = root.OIMO || this.OIMO;
  88. var earcut = root.earcut || this.earcut;
  89. if(true) {
  90. try { CANNON = CANNON || __webpack_require__(20); } catch(e) {}
  91. try { OIMO = OIMO || __webpack_require__(21); } catch(e) {}
  92. try { earcut = earcut || __webpack_require__(22); } catch(e) {}
  93. module.exports = factory(CANNON,OIMO,earcut);
  94. } else if(typeof define === 'function' && define.amd) {
  95. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  96. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  97. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  98. define("babylonjs", amdDependencies, factory);
  99. } else if(typeof exports === 'object') {
  100. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  101. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  102. try { earcut = earcut || require("earcut"); } catch(e) {}
  103. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  104. } else {
  105. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  106. }
  107. })(this, function(CANNON,OIMO,earcut) {
  108. CANNON = CANNON || this.CANNON;
  109. OIMO = OIMO || this.OIMO;
  110. earcut = earcut || this.earcut;
  111. "use strict";
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. var scene = this._mesh.getScene();
  183. for (var index = 0; index < scene.meshes.length; index++) {
  184. var otherMesh = scene.meshes[index];
  185. if (!otherMesh.material) {
  186. continue;
  187. }
  188. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  189. continue;
  190. }
  191. if (otherMesh.material.getEffect() === effect) {
  192. otherMesh.computeBonesUsingShaders = false;
  193. }
  194. else {
  195. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  196. var subMesh = _a[_i];
  197. var subMeshEffect = subMesh.effect;
  198. if (subMeshEffect === effect) {
  199. otherMesh.computeBonesUsingShaders = false;
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. else {
  207. var currentFallbacks = this._defines[this._currentRank];
  208. if (currentFallbacks) {
  209. for (var index = 0; index < currentFallbacks.length; index++) {
  210. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  211. }
  212. }
  213. this._currentRank++;
  214. }
  215. return currentDefines;
  216. };
  217. return EffectFallbacks;
  218. }());
  219. BABYLON.EffectFallbacks = EffectFallbacks;
  220. /**
  221. * Options to be used when creating an effect.
  222. */
  223. var EffectCreationOptions = /** @class */ (function () {
  224. function EffectCreationOptions() {
  225. }
  226. return EffectCreationOptions;
  227. }());
  228. BABYLON.EffectCreationOptions = EffectCreationOptions;
  229. /**
  230. * Effect containing vertex and fragment shader that can be executed on an object.
  231. */
  232. var Effect = /** @class */ (function () {
  233. /**
  234. * Instantiates an effect.
  235. * An effect can be used to create/manage/execute vertex and fragment shaders.
  236. * @param baseName Name of the effect.
  237. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  238. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  239. * @param samplers List of sampler variables that will be passed to the shader.
  240. * @param engine Engine to be used to render the effect
  241. * @param defines Define statements to be added to the shader.
  242. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  243. * @param onCompiled Callback that will be called when the shader is compiled.
  244. * @param onError Callback that will be called if an error occurs during shader compilation.
  245. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  246. */
  247. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  248. if (samplers === void 0) { samplers = null; }
  249. if (defines === void 0) { defines = null; }
  250. if (fallbacks === void 0) { fallbacks = null; }
  251. if (onCompiled === void 0) { onCompiled = null; }
  252. if (onError === void 0) { onError = null; }
  253. var _this = this;
  254. /**
  255. * Unique ID of the effect.
  256. */
  257. this.uniqueId = 0;
  258. /**
  259. * Observable that will be called when the shader is compiled.
  260. */
  261. this.onCompileObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called if an error occurs during shader compilation.
  264. */
  265. this.onErrorObservable = new BABYLON.Observable();
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. this.onBindObservable = new BABYLON.Observable();
  270. this._uniformBuffersNames = {};
  271. this._isReady = false;
  272. this._compilationError = "";
  273. this.name = baseName;
  274. if (attributesNamesOrOptions.attributes) {
  275. var options = attributesNamesOrOptions;
  276. this._engine = uniformsNamesOrEngine;
  277. this._attributesNames = options.attributes;
  278. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  279. this._samplers = options.samplers.slice();
  280. this.defines = options.defines;
  281. this.onError = options.onError;
  282. this.onCompiled = options.onCompiled;
  283. this._fallbacks = options.fallbacks;
  284. this._indexParameters = options.indexParameters;
  285. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  286. if (options.uniformBuffersNames) {
  287. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  288. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  289. }
  290. }
  291. }
  292. else {
  293. this._engine = engine;
  294. this.defines = defines;
  295. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  296. this._samplers = samplers ? samplers.slice() : [];
  297. this._attributesNames = attributesNamesOrOptions;
  298. this.onError = onError;
  299. this.onCompiled = onCompiled;
  300. this._indexParameters = indexParameters;
  301. this._fallbacks = fallbacks;
  302. }
  303. this.uniqueId = Effect._uniqueIdSeed++;
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. this._loadVertexShader(vertexSource, function (vertexCode) {
  325. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  326. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  327. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  328. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  329. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  330. if (baseName) {
  331. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  332. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  333. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  334. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  335. }
  336. else {
  337. _this._vertexSourceCode = migratedVertexCode;
  338. _this._fragmentSourceCode = migratedFragmentCode;
  339. }
  340. _this._prepareEffect();
  341. });
  342. });
  343. });
  344. });
  345. });
  346. });
  347. }
  348. Object.defineProperty(Effect.prototype, "key", {
  349. /**
  350. * Unique key for this effect
  351. */
  352. get: function () {
  353. return this._key;
  354. },
  355. enumerable: true,
  356. configurable: true
  357. });
  358. /**
  359. * If the effect has been compiled and prepared.
  360. * @returns if the effect is compiled and prepared.
  361. */
  362. Effect.prototype.isReady = function () {
  363. return this._isReady;
  364. };
  365. /**
  366. * The engine the effect was initialized with.
  367. * @returns the engine.
  368. */
  369. Effect.prototype.getEngine = function () {
  370. return this._engine;
  371. };
  372. /**
  373. * The compiled webGL program for the effect
  374. * @returns the webGL program.
  375. */
  376. Effect.prototype.getProgram = function () {
  377. return this._program;
  378. };
  379. /**
  380. * The set of names of attribute variables for the shader.
  381. * @returns An array of attribute names.
  382. */
  383. Effect.prototype.getAttributesNames = function () {
  384. return this._attributesNames;
  385. };
  386. /**
  387. * Returns the attribute at the given index.
  388. * @param index The index of the attribute.
  389. * @returns The location of the attribute.
  390. */
  391. Effect.prototype.getAttributeLocation = function (index) {
  392. return this._attributes[index];
  393. };
  394. /**
  395. * Returns the attribute based on the name of the variable.
  396. * @param name of the attribute to look up.
  397. * @returns the attribute location.
  398. */
  399. Effect.prototype.getAttributeLocationByName = function (name) {
  400. var index = this._attributesNames.indexOf(name);
  401. return this._attributes[index];
  402. };
  403. /**
  404. * The number of attributes.
  405. * @returns the numnber of attributes.
  406. */
  407. Effect.prototype.getAttributesCount = function () {
  408. return this._attributes.length;
  409. };
  410. /**
  411. * Gets the index of a uniform variable.
  412. * @param uniformName of the uniform to look up.
  413. * @returns the index.
  414. */
  415. Effect.prototype.getUniformIndex = function (uniformName) {
  416. return this._uniformsNames.indexOf(uniformName);
  417. };
  418. /**
  419. * Returns the attribute based on the name of the variable.
  420. * @param uniformName of the uniform to look up.
  421. * @returns the location of the uniform.
  422. */
  423. Effect.prototype.getUniform = function (uniformName) {
  424. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  425. };
  426. /**
  427. * Returns an array of sampler variable names
  428. * @returns The array of sampler variable neames.
  429. */
  430. Effect.prototype.getSamplers = function () {
  431. return this._samplers;
  432. };
  433. /**
  434. * The error from the last compilation.
  435. * @returns the error string.
  436. */
  437. Effect.prototype.getCompilationError = function () {
  438. return this._compilationError;
  439. };
  440. /**
  441. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  442. * @param func The callback to be used.
  443. */
  444. Effect.prototype.executeWhenCompiled = function (func) {
  445. if (this.isReady()) {
  446. func(this);
  447. return;
  448. }
  449. this.onCompileObservable.add(function (effect) {
  450. func(effect);
  451. });
  452. };
  453. /** @ignore */
  454. Effect.prototype._loadVertexShader = function (vertex, callback) {
  455. if (BABYLON.Tools.IsWindowObjectExist()) {
  456. // DOM element ?
  457. if (vertex instanceof HTMLElement) {
  458. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  459. callback(vertexCode);
  460. return;
  461. }
  462. }
  463. // Base64 encoded ?
  464. if (vertex.substr(0, 7) === "base64:") {
  465. var vertexBinary = window.atob(vertex.substr(7));
  466. callback(vertexBinary);
  467. return;
  468. }
  469. // Is in local store ?
  470. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  471. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  472. return;
  473. }
  474. var vertexShaderUrl;
  475. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  476. vertexShaderUrl = vertex;
  477. }
  478. else {
  479. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  480. }
  481. // Vertex shader
  482. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  483. };
  484. /** @ignore */
  485. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  486. if (BABYLON.Tools.IsWindowObjectExist()) {
  487. // DOM element ?
  488. if (fragment instanceof HTMLElement) {
  489. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  490. callback(fragmentCode);
  491. return;
  492. }
  493. }
  494. // Base64 encoded ?
  495. if (fragment.substr(0, 7) === "base64:") {
  496. var fragmentBinary = window.atob(fragment.substr(7));
  497. callback(fragmentBinary);
  498. return;
  499. }
  500. // Is in local store ?
  501. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  502. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  503. return;
  504. }
  505. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  506. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  507. return;
  508. }
  509. var fragmentShaderUrl;
  510. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  511. fragmentShaderUrl = fragment;
  512. }
  513. else {
  514. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  515. }
  516. // Fragment shader
  517. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  518. };
  519. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  520. // Rebuild shaders source code
  521. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  522. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  523. vertexCode = prefix + vertexCode;
  524. fragmentCode = prefix + fragmentCode;
  525. // Number lines of shaders source code
  526. var i = 2;
  527. var regex = /\n/gm;
  528. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  529. i = 2;
  530. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  531. // Dump shaders name and formatted source code
  532. if (this.name.vertexElement) {
  533. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  534. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  535. }
  536. else if (this.name.vertex) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  539. }
  540. else {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  543. }
  544. };
  545. ;
  546. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  547. var preparedSourceCode = this._processPrecision(sourceCode);
  548. if (this._engine.webGLVersion == 1) {
  549. callback(preparedSourceCode);
  550. return;
  551. }
  552. // Already converted
  553. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  554. callback(preparedSourceCode.replace("#version 300 es", ""));
  555. return;
  556. }
  557. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  558. // Remove extensions
  559. // #extension GL_OES_standard_derivatives : enable
  560. // #extension GL_EXT_shader_texture_lod : enable
  561. // #extension GL_EXT_frag_depth : enable
  562. // #extension GL_EXT_draw_buffers : require
  563. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  564. var result = preparedSourceCode.replace(regex, "");
  565. // Migrate to GLSL v300
  566. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  567. result = result.replace(/attribute[ \t]/g, "in ");
  568. result = result.replace(/[ \t]attribute/g, " in");
  569. if (isFragment) {
  570. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  571. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  572. result = result.replace(/texture2D\s*\(/g, "texture(");
  573. result = result.replace(/textureCube\s*\(/g, "texture(");
  574. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  575. result = result.replace(/gl_FragColor/g, "glFragColor");
  576. result = result.replace(/gl_FragData/g, "glFragData");
  577. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  578. }
  579. callback(result);
  580. };
  581. Effect.prototype._processIncludes = function (sourceCode, callback) {
  582. var _this = this;
  583. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  584. var match = regex.exec(sourceCode);
  585. var returnValue = new String(sourceCode);
  586. while (match != null) {
  587. var includeFile = match[1];
  588. // Uniform declaration
  589. if (includeFile.indexOf("__decl__") !== -1) {
  590. includeFile = includeFile.replace(/__decl__/, "");
  591. if (this._engine.supportsUniformBuffers) {
  592. includeFile = includeFile.replace(/Vertex/, "Ubo");
  593. includeFile = includeFile.replace(/Fragment/, "Ubo");
  594. }
  595. includeFile = includeFile + "Declaration";
  596. }
  597. if (Effect.IncludesShadersStore[includeFile]) {
  598. // Substitution
  599. var includeContent = Effect.IncludesShadersStore[includeFile];
  600. if (match[2]) {
  601. var splits = match[3].split(",");
  602. for (var index = 0; index < splits.length; index += 2) {
  603. var source = new RegExp(splits[index], "g");
  604. var dest = splits[index + 1];
  605. includeContent = includeContent.replace(source, dest);
  606. }
  607. }
  608. if (match[4]) {
  609. var indexString = match[5];
  610. if (indexString.indexOf("..") !== -1) {
  611. var indexSplits = indexString.split("..");
  612. var minIndex = parseInt(indexSplits[0]);
  613. var maxIndex = parseInt(indexSplits[1]);
  614. var sourceIncludeContent = includeContent.slice(0);
  615. includeContent = "";
  616. if (isNaN(maxIndex)) {
  617. maxIndex = this._indexParameters[indexSplits[1]];
  618. }
  619. for (var i = minIndex; i < maxIndex; i++) {
  620. if (!this._engine.supportsUniformBuffers) {
  621. // Ubo replacement
  622. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  623. return p1 + "{X}";
  624. });
  625. }
  626. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  627. }
  628. }
  629. else {
  630. if (!this._engine.supportsUniformBuffers) {
  631. // Ubo replacement
  632. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  633. return p1 + "{X}";
  634. });
  635. }
  636. includeContent = includeContent.replace(/\{X\}/g, indexString);
  637. }
  638. }
  639. // Replace
  640. returnValue = returnValue.replace(match[0], includeContent);
  641. }
  642. else {
  643. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  644. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  645. Effect.IncludesShadersStore[includeFile] = fileContent;
  646. _this._processIncludes(returnValue, callback);
  647. });
  648. return;
  649. }
  650. match = regex.exec(sourceCode);
  651. }
  652. callback(returnValue);
  653. };
  654. Effect.prototype._processPrecision = function (source) {
  655. if (source.indexOf("precision highp float") === -1) {
  656. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  657. source = "precision mediump float;\n" + source;
  658. }
  659. else {
  660. source = "precision highp float;\n" + source;
  661. }
  662. }
  663. else {
  664. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  665. source = source.replace("precision highp float", "precision mediump float");
  666. }
  667. }
  668. return source;
  669. };
  670. /**
  671. * Recompiles the webGL program
  672. * @param vertexSourceCode The source code for the vertex shader.
  673. * @param fragmentSourceCode The source code for the fragment shader.
  674. * @param onCompiled Callback called when completed.
  675. * @param onError Callback called on error.
  676. */
  677. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  678. var _this = this;
  679. this._isReady = false;
  680. this._vertexSourceCodeOverride = vertexSourceCode;
  681. this._fragmentSourceCodeOverride = fragmentSourceCode;
  682. this.onError = function (effect, error) {
  683. if (onError) {
  684. onError(error);
  685. }
  686. };
  687. this.onCompiled = function () {
  688. var scenes = _this.getEngine().scenes;
  689. for (var i = 0; i < scenes.length; i++) {
  690. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  691. }
  692. if (onCompiled) {
  693. onCompiled(_this._program);
  694. }
  695. };
  696. this._fallbacks = null;
  697. this._prepareEffect();
  698. };
  699. /**
  700. * Gets the uniform locations of the the specified variable names
  701. * @param names THe names of the variables to lookup.
  702. * @returns Array of locations in the same order as variable names.
  703. */
  704. Effect.prototype.getSpecificUniformLocations = function (names) {
  705. var engine = this._engine;
  706. return engine.getUniforms(this._program, names);
  707. };
  708. /**
  709. * Prepares the effect
  710. */
  711. Effect.prototype._prepareEffect = function () {
  712. var attributesNames = this._attributesNames;
  713. var defines = this.defines;
  714. var fallbacks = this._fallbacks;
  715. this._valueCache = {};
  716. var previousProgram = this._program;
  717. try {
  718. var engine = this._engine;
  719. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  720. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  721. }
  722. else {
  723. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  724. }
  725. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  726. if (engine.supportsUniformBuffers) {
  727. for (var name in this._uniformBuffersNames) {
  728. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  729. }
  730. }
  731. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  732. this._attributes = engine.getAttributes(this._program, attributesNames);
  733. var index;
  734. for (index = 0; index < this._samplers.length; index++) {
  735. var sampler = this.getUniform(this._samplers[index]);
  736. if (sampler == null) {
  737. this._samplers.splice(index, 1);
  738. index--;
  739. }
  740. }
  741. engine.bindSamplers(this);
  742. this._compilationError = "";
  743. this._isReady = true;
  744. if (this.onCompiled) {
  745. this.onCompiled(this);
  746. }
  747. this.onCompileObservable.notifyObservers(this);
  748. this.onCompileObservable.clear();
  749. // Unbind mesh reference in fallbacks
  750. if (this._fallbacks) {
  751. this._fallbacks.unBindMesh();
  752. }
  753. if (previousProgram) {
  754. this.getEngine()._deleteProgram(previousProgram);
  755. }
  756. }
  757. catch (e) {
  758. this._compilationError = e.message;
  759. // Let's go through fallbacks then
  760. BABYLON.Tools.Error("Unable to compile effect:");
  761. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  762. return " " + uniform;
  763. }));
  764. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  765. return " " + attribute;
  766. }));
  767. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  768. BABYLON.Tools.Error("Error: " + this._compilationError);
  769. if (previousProgram) {
  770. this._program = previousProgram;
  771. this._isReady = true;
  772. if (this.onError) {
  773. this.onError(this, this._compilationError);
  774. }
  775. this.onErrorObservable.notifyObservers(this);
  776. }
  777. if (fallbacks && fallbacks.isMoreFallbacks) {
  778. BABYLON.Tools.Error("Trying next fallback.");
  779. this.defines = fallbacks.reduce(this.defines, this);
  780. this._prepareEffect();
  781. }
  782. else {
  783. if (this.onError) {
  784. this.onError(this, this._compilationError);
  785. }
  786. this.onErrorObservable.notifyObservers(this);
  787. this.onErrorObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. }
  793. }
  794. };
  795. Object.defineProperty(Effect.prototype, "isSupported", {
  796. /**
  797. * Checks if the effect is supported. (Must be called after compilation)
  798. */
  799. get: function () {
  800. return this._compilationError === "";
  801. },
  802. enumerable: true,
  803. configurable: true
  804. });
  805. /**
  806. * Binds a texture to the engine to be used as output of the shader.
  807. * @param channel Name of the output variable.
  808. * @param texture Texture to bind.
  809. */
  810. Effect.prototype._bindTexture = function (channel, texture) {
  811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  812. };
  813. /**
  814. * Sets a texture on the engine to be used in the shader.
  815. * @param channel Name of the sampler variable.
  816. * @param texture Texture to set.
  817. */
  818. Effect.prototype.setTexture = function (channel, texture) {
  819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  820. };
  821. /**
  822. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  823. * @param channel Name of the sampler variable.
  824. * @param texture Texture to set.
  825. */
  826. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  827. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  828. };
  829. /**
  830. * Sets an array of textures on the engine to be used in the shader.
  831. * @param channel Name of the variable.
  832. * @param textures Textures to set.
  833. */
  834. Effect.prototype.setTextureArray = function (channel, textures) {
  835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  836. var initialPos = this._samplers.indexOf(channel);
  837. for (var index = 1; index < textures.length; index++) {
  838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  839. }
  840. }
  841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  842. };
  843. /**
  844. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  845. * @param channel Name of the sampler variable.
  846. * @param postProcess Post process to get the input texture from.
  847. */
  848. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  849. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  850. };
  851. /**
  852. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  853. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  854. * @param channel Name of the sampler variable.
  855. * @param postProcess Post process to get the output texture from.
  856. */
  857. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  858. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  859. };
  860. /** @ignore */
  861. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  862. var cache = this._valueCache[uniformName];
  863. var flag = matrix.updateFlag;
  864. if (cache !== undefined && cache === flag) {
  865. return false;
  866. }
  867. this._valueCache[uniformName] = flag;
  868. return true;
  869. };
  870. /** @ignore */
  871. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  872. var cache = this._valueCache[uniformName];
  873. if (!cache) {
  874. cache = [x, y];
  875. this._valueCache[uniformName] = cache;
  876. return true;
  877. }
  878. var changed = false;
  879. if (cache[0] !== x) {
  880. cache[0] = x;
  881. changed = true;
  882. }
  883. if (cache[1] !== y) {
  884. cache[1] = y;
  885. changed = true;
  886. }
  887. return changed;
  888. };
  889. /** @ignore */
  890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  891. var cache = this._valueCache[uniformName];
  892. if (!cache) {
  893. cache = [x, y, z];
  894. this._valueCache[uniformName] = cache;
  895. return true;
  896. }
  897. var changed = false;
  898. if (cache[0] !== x) {
  899. cache[0] = x;
  900. changed = true;
  901. }
  902. if (cache[1] !== y) {
  903. cache[1] = y;
  904. changed = true;
  905. }
  906. if (cache[2] !== z) {
  907. cache[2] = z;
  908. changed = true;
  909. }
  910. return changed;
  911. };
  912. /** @ignore */
  913. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  914. var cache = this._valueCache[uniformName];
  915. if (!cache) {
  916. cache = [x, y, z, w];
  917. this._valueCache[uniformName] = cache;
  918. return true;
  919. }
  920. var changed = false;
  921. if (cache[0] !== x) {
  922. cache[0] = x;
  923. changed = true;
  924. }
  925. if (cache[1] !== y) {
  926. cache[1] = y;
  927. changed = true;
  928. }
  929. if (cache[2] !== z) {
  930. cache[2] = z;
  931. changed = true;
  932. }
  933. if (cache[3] !== w) {
  934. cache[3] = w;
  935. changed = true;
  936. }
  937. return changed;
  938. };
  939. /**
  940. * Binds a buffer to a uniform.
  941. * @param buffer Buffer to bind.
  942. * @param name Name of the uniform variable to bind to.
  943. */
  944. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  945. var bufferName = this._uniformBuffersNames[name];
  946. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  947. return;
  948. }
  949. Effect._baseCache[bufferName] = buffer;
  950. this._engine.bindUniformBufferBase(buffer, bufferName);
  951. };
  952. /**
  953. * Binds block to a uniform.
  954. * @param blockName Name of the block to bind.
  955. * @param index Index to bind.
  956. */
  957. Effect.prototype.bindUniformBlock = function (blockName, index) {
  958. this._engine.bindUniformBlock(this._program, blockName, index);
  959. };
  960. /**
  961. * Sets an interger value on a uniform variable.
  962. * @param uniformName Name of the variable.
  963. * @param value Value to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setInt = function (uniformName, value) {
  967. var cache = this._valueCache[uniformName];
  968. if (cache !== undefined && cache === value)
  969. return this;
  970. this._valueCache[uniformName] = value;
  971. this._engine.setInt(this.getUniform(uniformName), value);
  972. return this;
  973. };
  974. /**
  975. * Sets an int array on a uniform variable.
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setIntArray = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setIntArray(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setIntArray2 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setIntArray2(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * Sets an float array on a uniform variable.
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setFloatArray = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1042. * @param uniformName Name of the variable.
  1043. * @param array array to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1053. * @param uniformName Name of the variable.
  1054. * @param array array to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets an array on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param array array to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setArray = function (uniformName, array) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setArray(this.getUniform(uniformName), array);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1075. * @param uniformName Name of the variable.
  1076. * @param array array to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setArray2 = function (uniformName, array) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setArray2(this.getUniform(uniformName), array);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1086. * @param uniformName Name of the variable.
  1087. * @param array array to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setArray3 = function (uniformName, array) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setArray3(this.getUniform(uniformName), array);
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1097. * @param uniformName Name of the variable.
  1098. * @param array array to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setArray4 = function (uniformName, array) {
  1102. this._valueCache[uniformName] = null;
  1103. this._engine.setArray4(this.getUniform(uniformName), array);
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets matrices on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param matrices matrices to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1113. if (!matrices) {
  1114. return this;
  1115. }
  1116. this._valueCache[uniformName] = null;
  1117. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1118. return this;
  1119. };
  1120. /**
  1121. * Sets matrix on a uniform variable.
  1122. * @param uniformName Name of the variable.
  1123. * @param matrix matrix to be set.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1127. if (this._cacheMatrix(uniformName, matrix)) {
  1128. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1134. * @param uniformName Name of the variable.
  1135. * @param matrix matrix to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1139. this._valueCache[uniformName] = null;
  1140. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1145. * @param uniformName Name of the variable.
  1146. * @param matrix matrix to be set.
  1147. * @returns this effect.
  1148. */
  1149. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1150. this._valueCache[uniformName] = null;
  1151. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param value value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat = function (uniformName, value) {
  1161. var cache = this._valueCache[uniformName];
  1162. if (cache !== undefined && cache === value)
  1163. return this;
  1164. this._valueCache[uniformName] = value;
  1165. this._engine.setFloat(this.getUniform(uniformName), value);
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a boolean on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param bool value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setBool = function (uniformName, bool) {
  1175. var cache = this._valueCache[uniformName];
  1176. if (cache !== undefined && cache === bool)
  1177. return this;
  1178. this._valueCache[uniformName] = bool;
  1179. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a Vector2 on a uniform variable.
  1184. * @param uniformName Name of the variable.
  1185. * @param vector2 vector2 to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1189. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1190. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a float2 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param x First float in float2.
  1198. * @param y Second float in float2.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1202. if (this._cacheFloat2(uniformName, x, y)) {
  1203. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Vector3 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param vector3 Value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1214. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1215. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a float3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param x First float in float3.
  1223. * @param y Second float in float3.
  1224. * @param z Third float in float3.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1228. if (this._cacheFloat3(uniformName, x, y, z)) {
  1229. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a Vector4 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param vector4 Value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1240. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1241. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a float4 on a uniform variable.
  1247. * @param uniformName Name of the variable.
  1248. * @param x First float in float4.
  1249. * @param y Second float in float4.
  1250. * @param z Third float in float4.
  1251. * @param w Fourth float in float4.
  1252. * @returns this effect.
  1253. */
  1254. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1255. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1256. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1257. }
  1258. return this;
  1259. };
  1260. /**
  1261. * Sets a Color3 on a uniform variable.
  1262. * @param uniformName Name of the variable.
  1263. * @param color3 Value to be set.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setColor3 = function (uniformName, color3) {
  1267. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1268. this._engine.setColor3(this.getUniform(uniformName), color3);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Color4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param color3 Value to be set.
  1276. * @param alpha Alpha value to be set.
  1277. * @returns this effect.
  1278. */
  1279. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1280. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1281. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1282. }
  1283. return this;
  1284. };
  1285. /**
  1286. * Sets a Color4 on a uniform variable
  1287. * @param uniformName defines the name of the variable
  1288. * @param color4 defines the value to be set
  1289. * @returns this effect.
  1290. */
  1291. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1292. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1293. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1294. }
  1295. return this;
  1296. };
  1297. /**
  1298. * Resets the cache of effects.
  1299. */
  1300. Effect.ResetCache = function () {
  1301. Effect._baseCache = {};
  1302. };
  1303. Effect._uniqueIdSeed = 0;
  1304. Effect._baseCache = {};
  1305. /**
  1306. * Store of each shader (The can be looked up using effect.key)
  1307. */
  1308. Effect.ShadersStore = {};
  1309. /**
  1310. * Store of each included file for a shader (The can be looked up using effect.key)
  1311. */
  1312. Effect.IncludesShadersStore = {};
  1313. return Effect;
  1314. }());
  1315. BABYLON.Effect = Effect;
  1316. })(BABYLON || (BABYLON = {}));
  1317. //# sourceMappingURL=babylon.effect.js.map
  1318. "use strict";
  1319. //# sourceMappingURL=babylon.types.js.map
  1320. "use strict";
  1321. var BABYLON;
  1322. (function (BABYLON) {
  1323. var KeyboardEventTypes = /** @class */ (function () {
  1324. function KeyboardEventTypes() {
  1325. }
  1326. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1327. get: function () {
  1328. return KeyboardEventTypes._KEYDOWN;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1334. get: function () {
  1335. return KeyboardEventTypes._KEYUP;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. KeyboardEventTypes._KEYDOWN = 0x01;
  1341. KeyboardEventTypes._KEYUP = 0x02;
  1342. return KeyboardEventTypes;
  1343. }());
  1344. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1345. var KeyboardInfo = /** @class */ (function () {
  1346. function KeyboardInfo(type, event) {
  1347. this.type = type;
  1348. this.event = event;
  1349. }
  1350. return KeyboardInfo;
  1351. }());
  1352. BABYLON.KeyboardInfo = KeyboardInfo;
  1353. /**
  1354. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1355. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1356. */
  1357. var KeyboardInfoPre = /** @class */ (function (_super) {
  1358. __extends(KeyboardInfoPre, _super);
  1359. function KeyboardInfoPre(type, event) {
  1360. var _this = _super.call(this, type, event) || this;
  1361. _this.skipOnPointerObservable = false;
  1362. return _this;
  1363. }
  1364. return KeyboardInfoPre;
  1365. }(KeyboardInfo));
  1366. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1367. })(BABYLON || (BABYLON = {}));
  1368. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1369. "use strict";
  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. _this.skipOnPointerObservable = false;
  1451. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1452. return _this;
  1453. }
  1454. return PointerInfoPre;
  1455. }(PointerInfoBase));
  1456. BABYLON.PointerInfoPre = PointerInfoPre;
  1457. /**
  1458. * This type contains all the data related to a pointer event in Babylon.js.
  1459. * 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.
  1460. */
  1461. var PointerInfo = /** @class */ (function (_super) {
  1462. __extends(PointerInfo, _super);
  1463. function PointerInfo(type, event, pickInfo) {
  1464. var _this = _super.call(this, type, event) || this;
  1465. _this.pickInfo = pickInfo;
  1466. return _this;
  1467. }
  1468. return PointerInfo;
  1469. }(PointerInfoBase));
  1470. BABYLON.PointerInfo = PointerInfo;
  1471. })(BABYLON || (BABYLON = {}));
  1472. //# sourceMappingURL=babylon.pointerEvents.js.map
  1473. "use strict";
  1474. var BABYLON;
  1475. (function (BABYLON) {
  1476. BABYLON.ToGammaSpace = 1 / 2.2;
  1477. BABYLON.ToLinearSpace = 2.2;
  1478. BABYLON.Epsilon = 0.001;
  1479. /**
  1480. * Class used to hold a RBG color
  1481. */
  1482. var Color3 = /** @class */ (function () {
  1483. /**
  1484. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1485. * @param r defines the red component (between 0 and 1, default is 0)
  1486. * @param g defines the green component (between 0 and 1, default is 0)
  1487. * @param b defines the blue component (between 0 and 1, default is 0)
  1488. */
  1489. function Color3(
  1490. /**
  1491. * Defines the red component (between 0 and 1, default is 0)
  1492. */
  1493. r,
  1494. /**
  1495. * Defines the green component (between 0 and 1, default is 0)
  1496. */
  1497. g,
  1498. /**
  1499. * Defines the blue component (between 0 and 1, default is 0)
  1500. */
  1501. b) {
  1502. if (r === void 0) { r = 0; }
  1503. if (g === void 0) { g = 0; }
  1504. if (b === void 0) { b = 0; }
  1505. this.r = r;
  1506. this.g = g;
  1507. this.b = b;
  1508. }
  1509. /**
  1510. * Creates a string with the Color3 current values
  1511. * @returns the string representation of the Color3 object
  1512. */
  1513. Color3.prototype.toString = function () {
  1514. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1515. };
  1516. /**
  1517. * Returns the string "Color3"
  1518. * @returns "Color3"
  1519. */
  1520. Color3.prototype.getClassName = function () {
  1521. return "Color3";
  1522. };
  1523. /**
  1524. * Compute the Color3 hash code
  1525. * @returns an unique number that can be used to hash Color3 objects
  1526. */
  1527. Color3.prototype.getHashCode = function () {
  1528. var hash = this.r || 0;
  1529. hash = (hash * 397) ^ (this.g || 0);
  1530. hash = (hash * 397) ^ (this.b || 0);
  1531. return hash;
  1532. };
  1533. // Operators
  1534. /**
  1535. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1536. * @param array defines the array where to store the r,g,b components
  1537. * @param index defines an optional index in the target array to define where to start storing values
  1538. * @returns the current Color3 object
  1539. */
  1540. Color3.prototype.toArray = function (array, index) {
  1541. if (index === undefined) {
  1542. index = 0;
  1543. }
  1544. array[index] = this.r;
  1545. array[index + 1] = this.g;
  1546. array[index + 2] = this.b;
  1547. return this;
  1548. };
  1549. /**
  1550. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1551. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1552. * @returns a new {BABYLON.Color4} object
  1553. */
  1554. Color3.prototype.toColor4 = function (alpha) {
  1555. if (alpha === void 0) { alpha = 1; }
  1556. return new Color4(this.r, this.g, this.b, alpha);
  1557. };
  1558. /**
  1559. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1560. * @returns the new array
  1561. */
  1562. Color3.prototype.asArray = function () {
  1563. var result = new Array();
  1564. this.toArray(result, 0);
  1565. return result;
  1566. };
  1567. /**
  1568. * Returns the luminance value
  1569. * @returns a float value
  1570. */
  1571. Color3.prototype.toLuminance = function () {
  1572. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1573. };
  1574. /**
  1575. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1576. * @param otherColor defines the second operand
  1577. * @returns the new Color3 object
  1578. */
  1579. Color3.prototype.multiply = function (otherColor) {
  1580. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1581. };
  1582. /**
  1583. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1584. * @param otherColor defines the second operand
  1585. * @param result defines the Color3 object where to store the result
  1586. * @returns the current Color3
  1587. */
  1588. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1589. result.r = this.r * otherColor.r;
  1590. result.g = this.g * otherColor.g;
  1591. result.b = this.b * otherColor.b;
  1592. return this;
  1593. };
  1594. /**
  1595. * Determines equality between Color3 objects
  1596. * @param otherColor defines the second operand
  1597. * @returns true if the rgb values are equal to the passed ones
  1598. */
  1599. Color3.prototype.equals = function (otherColor) {
  1600. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1601. };
  1602. /**
  1603. * Determines equality between the current Color3 object and a set of r,b,g values
  1604. * @param r defines the red component to check
  1605. * @param g defines the green component to check
  1606. * @param b defines the blue component to check
  1607. * @returns true if the rgb values are equal to the passed ones
  1608. */
  1609. Color3.prototype.equalsFloats = function (r, g, b) {
  1610. return this.r === r && this.g === g && this.b === b;
  1611. };
  1612. /**
  1613. * Multiplies in place each rgb value by scale
  1614. * @param scale defines the scaling factor
  1615. * @returns the updated Color3
  1616. */
  1617. Color3.prototype.scale = function (scale) {
  1618. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1619. };
  1620. /**
  1621. * Multiplies the rgb values by scale and stores the result into "result"
  1622. * @param scale defines the scaling factor
  1623. * @param result defines the Color3 object where to store the result
  1624. * @returns the unmodified current Color3
  1625. */
  1626. Color3.prototype.scaleToRef = function (scale, result) {
  1627. result.r = this.r * scale;
  1628. result.g = this.g * scale;
  1629. result.b = this.b * scale;
  1630. return this;
  1631. };
  1632. /**
  1633. * Scale the current Color3 values by a factor and add the result to a given Color3
  1634. * @param scale defines the scale factor
  1635. * @param result defines color to store the result into
  1636. * @returns the unmodified current Color3
  1637. */
  1638. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1639. result.r += this.r * scale;
  1640. result.g += this.g * scale;
  1641. result.b += this.b * scale;
  1642. return this;
  1643. };
  1644. /**
  1645. * Clamps the rgb values by the min and max values and stores the result into "result"
  1646. * @param min defines minimum clamping value (default is 0)
  1647. * @param max defines maximum clamping value (default is 1)
  1648. * @param result defines color to store the result into
  1649. * @returns the original Color3
  1650. */
  1651. Color3.prototype.clampToRef = function (min, max, result) {
  1652. if (min === void 0) { min = 0; }
  1653. if (max === void 0) { max = 1; }
  1654. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1655. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1656. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1657. return this;
  1658. };
  1659. /**
  1660. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1661. * @param otherColor defines the second operand
  1662. * @returns the new Color3
  1663. */
  1664. Color3.prototype.add = function (otherColor) {
  1665. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1666. };
  1667. /**
  1668. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1669. * @param otherColor defines the second operand
  1670. * @param result defines Color3 object to store the result into
  1671. * @returns the unmodified current Color3
  1672. */
  1673. Color3.prototype.addToRef = function (otherColor, result) {
  1674. result.r = this.r + otherColor.r;
  1675. result.g = this.g + otherColor.g;
  1676. result.b = this.b + otherColor.b;
  1677. return this;
  1678. };
  1679. /**
  1680. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1681. * @param otherColor defines the second operand
  1682. * @returns the new Color3
  1683. */
  1684. Color3.prototype.subtract = function (otherColor) {
  1685. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1686. };
  1687. /**
  1688. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1689. * @param otherColor defines the second operand
  1690. * @param result defines Color3 object to store the result into
  1691. * @returns the unmodified current Color3
  1692. */
  1693. Color3.prototype.subtractToRef = function (otherColor, result) {
  1694. result.r = this.r - otherColor.r;
  1695. result.g = this.g - otherColor.g;
  1696. result.b = this.b - otherColor.b;
  1697. return this;
  1698. };
  1699. /**
  1700. * Copy the current object
  1701. * @returns a new Color3 copied the current one
  1702. */
  1703. Color3.prototype.clone = function () {
  1704. return new Color3(this.r, this.g, this.b);
  1705. };
  1706. /**
  1707. * Copies the rgb values from the source in the current Color3
  1708. * @param source defines the source Color3 object
  1709. * @returns the updated Color3 object
  1710. */
  1711. Color3.prototype.copyFrom = function (source) {
  1712. this.r = source.r;
  1713. this.g = source.g;
  1714. this.b = source.b;
  1715. return this;
  1716. };
  1717. /**
  1718. * Updates the Color3 rgb values from the passed floats
  1719. * @param r defines the red component to read from
  1720. * @param g defines the green component to read from
  1721. * @param b defines the blue component to read from
  1722. * @returns the current Color3 object
  1723. */
  1724. Color3.prototype.copyFromFloats = function (r, g, b) {
  1725. this.r = r;
  1726. this.g = g;
  1727. this.b = b;
  1728. return this;
  1729. };
  1730. /**
  1731. * Updates the Color3 rgb values from the passed floats
  1732. * @param r defines the red component to read from
  1733. * @param g defines the green component to read from
  1734. * @param b defines the blue component to read from
  1735. * @returns the current Color3 object
  1736. */
  1737. Color3.prototype.set = function (r, g, b) {
  1738. return this.copyFromFloats(r, g, b);
  1739. };
  1740. /**
  1741. * Compute the Color3 hexadecimal code as a string
  1742. * @returns a string containing the hexadecimal representation of the Color3 object
  1743. */
  1744. Color3.prototype.toHexString = function () {
  1745. var intR = (this.r * 255) | 0;
  1746. var intG = (this.g * 255) | 0;
  1747. var intB = (this.b * 255) | 0;
  1748. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1749. };
  1750. /**
  1751. * Computes a new Color3 converted from the current one to linear space
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.prototype.toLinearSpace = function () {
  1755. var convertedColor = new Color3();
  1756. this.toLinearSpaceToRef(convertedColor);
  1757. return convertedColor;
  1758. };
  1759. /**
  1760. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1761. * @param convertedColor defines the Color3 object where to store the linear space version
  1762. * @returns the unmodified Color3
  1763. */
  1764. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1765. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1766. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1767. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1768. return this;
  1769. };
  1770. /**
  1771. * Computes a new Color3 converted from the current one to gamma space
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.prototype.toGammaSpace = function () {
  1775. var convertedColor = new Color3();
  1776. this.toGammaSpaceToRef(convertedColor);
  1777. return convertedColor;
  1778. };
  1779. /**
  1780. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1781. * @param convertedColor defines the Color3 object where to store the gamma space version
  1782. * @returns the unmodified Color3
  1783. */
  1784. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1785. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1786. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1787. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1788. return this;
  1789. };
  1790. // Statics
  1791. /**
  1792. * Creates a new Color3 from the string containing valid hexadecimal values
  1793. * @param hex defines a string containing valid hexadecimal values
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.FromHexString = function (hex) {
  1797. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1798. return new Color3(0, 0, 0);
  1799. }
  1800. var r = parseInt(hex.substring(1, 3), 16);
  1801. var g = parseInt(hex.substring(3, 5), 16);
  1802. var b = parseInt(hex.substring(5, 7), 16);
  1803. return Color3.FromInts(r, g, b);
  1804. };
  1805. /**
  1806. * Creates a new Vector3 from the starting index of the passed array
  1807. * @param array defines the source array
  1808. * @param offset defines an offset in the source array
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.FromArray = function (array, offset) {
  1812. if (offset === void 0) { offset = 0; }
  1813. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1814. };
  1815. /**
  1816. * Creates a new Color3 from integer values (< 256)
  1817. * @param r defines the red component to read from (value between 0 and 255)
  1818. * @param g defines the green component to read from (value between 0 and 255)
  1819. * @param b defines the blue component to read from (value between 0 and 255)
  1820. * @returns a new Color3 object
  1821. */
  1822. Color3.FromInts = function (r, g, b) {
  1823. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1824. };
  1825. /**
  1826. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1827. * @param start defines the start Color3 value
  1828. * @param end defines the end Color3 value
  1829. * @param amount defines the gradient value between start and end
  1830. * @returns a new Color3 object
  1831. */
  1832. Color3.Lerp = function (start, end, amount) {
  1833. var r = start.r + ((end.r - start.r) * amount);
  1834. var g = start.g + ((end.g - start.g) * amount);
  1835. var b = start.b + ((end.b - start.b) * amount);
  1836. return new Color3(r, g, b);
  1837. };
  1838. /**
  1839. * Returns a Color3 value containing a red color
  1840. * @returns a new Color3 object
  1841. */
  1842. Color3.Red = function () { return new Color3(1, 0, 0); };
  1843. /**
  1844. * Returns a Color3 value containing a green color
  1845. * @returns a new Color3 object
  1846. */
  1847. Color3.Green = function () { return new Color3(0, 1, 0); };
  1848. /**
  1849. * Returns a Color3 value containing a blue color
  1850. * @returns a new Color3 object
  1851. */
  1852. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1853. /**
  1854. * Returns a Color3 value containing a black color
  1855. * @returns a new Color3 object
  1856. */
  1857. Color3.Black = function () { return new Color3(0, 0, 0); };
  1858. /**
  1859. * Returns a Color3 value containing a white color
  1860. * @returns a new Color3 object
  1861. */
  1862. Color3.White = function () { return new Color3(1, 1, 1); };
  1863. /**
  1864. * Returns a Color3 value containing a purple color
  1865. * @returns a new Color3 object
  1866. */
  1867. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1868. /**
  1869. * Returns a Color3 value containing a magenta color
  1870. * @returns a new Color3 object
  1871. */
  1872. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1873. /**
  1874. * Returns a Color3 value containing a yellow color
  1875. * @returns a new Color3 object
  1876. */
  1877. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1878. /**
  1879. * Returns a Color3 value containing a gray color
  1880. * @returns a new Color3 object
  1881. */
  1882. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1883. /**
  1884. * Returns a Color3 value containing a teal color
  1885. * @returns a new Color3 object
  1886. */
  1887. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1888. /**
  1889. * Returns a Color3 value containing a random color
  1890. * @returns a new Color3 object
  1891. */
  1892. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1893. return Color3;
  1894. }());
  1895. BABYLON.Color3 = Color3;
  1896. /**
  1897. * Class used to hold a RBGA color
  1898. */
  1899. var Color4 = /** @class */ (function () {
  1900. /**
  1901. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1902. * @param r defines the red component (between 0 and 1, default is 0)
  1903. * @param g defines the green component (between 0 and 1, default is 0)
  1904. * @param b defines the blue component (between 0 and 1, default is 0)
  1905. * @param a defines the alpha component (between 0 and 1, default is 1)
  1906. */
  1907. function Color4(
  1908. /**
  1909. * Defines the red component (between 0 and 1, default is 0)
  1910. */
  1911. r,
  1912. /**
  1913. * Defines the green component (between 0 and 1, default is 0)
  1914. */
  1915. g,
  1916. /**
  1917. * Defines the blue component (between 0 and 1, default is 0)
  1918. */
  1919. b,
  1920. /**
  1921. * Defines the alpha component (between 0 and 1, default is 1)
  1922. */
  1923. a) {
  1924. if (r === void 0) { r = 0; }
  1925. if (g === void 0) { g = 0; }
  1926. if (b === void 0) { b = 0; }
  1927. if (a === void 0) { a = 1; }
  1928. this.r = r;
  1929. this.g = g;
  1930. this.b = b;
  1931. this.a = a;
  1932. }
  1933. // Operators
  1934. /**
  1935. * Adds in place the passed Color4 values to the current Color4 object
  1936. * @param right defines the second operand
  1937. * @returns the current updated Color4 object
  1938. */
  1939. Color4.prototype.addInPlace = function (right) {
  1940. this.r += right.r;
  1941. this.g += right.g;
  1942. this.b += right.b;
  1943. this.a += right.a;
  1944. return this;
  1945. };
  1946. /**
  1947. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1948. * @returns the new array
  1949. */
  1950. Color4.prototype.asArray = function () {
  1951. var result = new Array();
  1952. this.toArray(result, 0);
  1953. return result;
  1954. };
  1955. /**
  1956. * Stores from the starting index in the passed array the Color4 successive values
  1957. * @param array defines the array where to store the r,g,b components
  1958. * @param index defines an optional index in the target array to define where to start storing values
  1959. * @returns the current Color4 object
  1960. */
  1961. Color4.prototype.toArray = function (array, index) {
  1962. if (index === undefined) {
  1963. index = 0;
  1964. }
  1965. array[index] = this.r;
  1966. array[index + 1] = this.g;
  1967. array[index + 2] = this.b;
  1968. array[index + 3] = this.a;
  1969. return this;
  1970. };
  1971. /**
  1972. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1973. * @param right defines the second operand
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.add = function (right) {
  1977. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1978. };
  1979. /**
  1980. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1981. * @param right defines the second operand
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.subtract = function (right) {
  1985. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1986. };
  1987. /**
  1988. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1989. * @param right defines the second operand
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current Color4 object
  1992. */
  1993. Color4.prototype.subtractToRef = function (right, result) {
  1994. result.r = this.r - right.r;
  1995. result.g = this.g - right.g;
  1996. result.b = this.b - right.b;
  1997. result.a = this.a - right.a;
  1998. return this;
  1999. };
  2000. /**
  2001. * Creates a new Color4 with the current Color4 values multiplied by scale
  2002. * @param scale defines the scaling factor to apply
  2003. * @returns a new Color4 object
  2004. */
  2005. Color4.prototype.scale = function (scale) {
  2006. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2007. };
  2008. /**
  2009. * Multiplies the current Color4 values by scale and stores the result in "result"
  2010. * @param scale defines the scaling factor to apply
  2011. * @param result defines the Color4 object where to store the result
  2012. * @returns the current unmodified Color4
  2013. */
  2014. Color4.prototype.scaleToRef = function (scale, result) {
  2015. result.r = this.r * scale;
  2016. result.g = this.g * scale;
  2017. result.b = this.b * scale;
  2018. result.a = this.a * scale;
  2019. return this;
  2020. };
  2021. /**
  2022. * Scale the current Color4 values by a factor and add the result to a given Color4
  2023. * @param scale defines the scale factor
  2024. * @param result defines the Color4 object where to store the result
  2025. * @returns the unmodified current Color4
  2026. */
  2027. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2028. result.r += this.r * scale;
  2029. result.g += this.g * scale;
  2030. result.b += this.b * scale;
  2031. result.a += this.a * scale;
  2032. return this;
  2033. };
  2034. /**
  2035. * Clamps the rgb values by the min and max values and stores the result into "result"
  2036. * @param min defines minimum clamping value (default is 0)
  2037. * @param max defines maximum clamping value (default is 1)
  2038. * @param result defines color to store the result into.
  2039. * @returns the cuurent Color4
  2040. */
  2041. Color4.prototype.clampToRef = function (min, max, result) {
  2042. if (min === void 0) { min = 0; }
  2043. if (max === void 0) { max = 1; }
  2044. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2045. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2046. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2047. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2048. return this;
  2049. };
  2050. /**
  2051. * Multipy an Color4 value by another and return a new Color4 object
  2052. * @param color defines the Color4 value to multiply by
  2053. * @returns a new Color4 object
  2054. */
  2055. Color4.prototype.multiply = function (color) {
  2056. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2057. };
  2058. /**
  2059. * Multipy a Color4 value by another and push the result in a reference value
  2060. * @param color defines the Color4 value to multiply by
  2061. * @param result defines the Color4 to fill the result in
  2062. * @returns the result Color4
  2063. */
  2064. Color4.prototype.multiplyToRef = function (color, result) {
  2065. result.r = this.r * color.r;
  2066. result.g = this.g * color.g;
  2067. result.b = this.b * color.b;
  2068. result.a = this.a * color.a;
  2069. return result;
  2070. };
  2071. /**
  2072. * Creates a string with the Color4 current values
  2073. * @returns the string representation of the Color4 object
  2074. */
  2075. Color4.prototype.toString = function () {
  2076. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2077. };
  2078. /**
  2079. * Returns the string "Color4"
  2080. * @returns "Color4"
  2081. */
  2082. Color4.prototype.getClassName = function () {
  2083. return "Color4";
  2084. };
  2085. /**
  2086. * Compute the Color4 hash code
  2087. * @returns an unique number that can be used to hash Color4 objects
  2088. */
  2089. Color4.prototype.getHashCode = function () {
  2090. var hash = this.r || 0;
  2091. hash = (hash * 397) ^ (this.g || 0);
  2092. hash = (hash * 397) ^ (this.b || 0);
  2093. hash = (hash * 397) ^ (this.a || 0);
  2094. return hash;
  2095. };
  2096. /**
  2097. * Creates a new Color4 copied from the current one
  2098. * @returns a new Color4 object
  2099. */
  2100. Color4.prototype.clone = function () {
  2101. return new Color4(this.r, this.g, this.b, this.a);
  2102. };
  2103. /**
  2104. * Copies the passed Color4 values into the current one
  2105. * @param source defines the source Color4 object
  2106. * @returns the current updated Color4 object
  2107. */
  2108. Color4.prototype.copyFrom = function (source) {
  2109. this.r = source.r;
  2110. this.g = source.g;
  2111. this.b = source.b;
  2112. this.a = source.a;
  2113. return this;
  2114. };
  2115. /**
  2116. * Copies the passed float values into the current one
  2117. * @param r defines the red component to read from
  2118. * @param g defines the green component to read from
  2119. * @param b defines the blue component to read from
  2120. * @param a defines the alpha component to read from
  2121. * @returns the current updated Color4 object
  2122. */
  2123. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2124. this.r = r;
  2125. this.g = g;
  2126. this.b = b;
  2127. this.a = a;
  2128. return this;
  2129. };
  2130. /**
  2131. * Copies the passed float values into the current one
  2132. * @param r defines the red component to read from
  2133. * @param g defines the green component to read from
  2134. * @param b defines the blue component to read from
  2135. * @param a defines the alpha component to read from
  2136. * @returns the current updated Color4 object
  2137. */
  2138. Color4.prototype.set = function (r, g, b, a) {
  2139. return this.copyFromFloats(r, g, b, a);
  2140. };
  2141. /**
  2142. * Compute the Color4 hexadecimal code as a string
  2143. * @returns a string containing the hexadecimal representation of the Color4 object
  2144. */
  2145. Color4.prototype.toHexString = function () {
  2146. var intR = (this.r * 255) | 0;
  2147. var intG = (this.g * 255) | 0;
  2148. var intB = (this.b * 255) | 0;
  2149. var intA = (this.a * 255) | 0;
  2150. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to linear space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toLinearSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toLinearSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the linear space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. /**
  2174. * Computes a new Color4 converted from the current one to gamma space
  2175. * @returns a new Color4 object
  2176. */
  2177. Color4.prototype.toGammaSpace = function () {
  2178. var convertedColor = new Color4();
  2179. this.toGammaSpaceToRef(convertedColor);
  2180. return convertedColor;
  2181. };
  2182. /**
  2183. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2184. * @param convertedColor defines the Color4 object where to store the gamma space version
  2185. * @returns the unmodified Color4
  2186. */
  2187. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2188. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2189. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2190. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2191. convertedColor.a = this.a;
  2192. return this;
  2193. };
  2194. // Statics
  2195. /**
  2196. * Creates a new Color4 from the string containing valid hexadecimal values
  2197. * @param hex defines a string containing valid hexadecimal values
  2198. * @returns a new Color4 object
  2199. */
  2200. Color4.FromHexString = function (hex) {
  2201. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2202. return new Color4(0.0, 0.0, 0.0, 0.0);
  2203. }
  2204. var r = parseInt(hex.substring(1, 3), 16);
  2205. var g = parseInt(hex.substring(3, 5), 16);
  2206. var b = parseInt(hex.substring(5, 7), 16);
  2207. var a = parseInt(hex.substring(7, 9), 16);
  2208. return Color4.FromInts(r, g, b, a);
  2209. };
  2210. /**
  2211. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2212. * @param left defines the start value
  2213. * @param right defines the end value
  2214. * @param amount defines the gradient factor
  2215. * @returns a new Color4 object
  2216. */
  2217. Color4.Lerp = function (left, right, amount) {
  2218. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2219. Color4.LerpToRef(left, right, amount, result);
  2220. return result;
  2221. };
  2222. /**
  2223. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2224. * @param left defines the start value
  2225. * @param right defines the end value
  2226. * @param amount defines the gradient factor
  2227. * @param result defines the Color4 object where to store data
  2228. */
  2229. Color4.LerpToRef = function (left, right, amount, result) {
  2230. result.r = left.r + (right.r - left.r) * amount;
  2231. result.g = left.g + (right.g - left.g) * amount;
  2232. result.b = left.b + (right.b - left.b) * amount;
  2233. result.a = left.a + (right.a - left.a) * amount;
  2234. };
  2235. /**
  2236. * Creates a new Color4 from the starting index element of the passed array
  2237. * @param array defines the source array to read from
  2238. * @param offset defines the offset in the source array
  2239. * @returns a new Color4 object
  2240. */
  2241. Color4.FromArray = function (array, offset) {
  2242. if (offset === void 0) { offset = 0; }
  2243. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2244. };
  2245. /**
  2246. * Creates a new Color3 from integer values (< 256)
  2247. * @param r defines the red component to read from (value between 0 and 255)
  2248. * @param g defines the green component to read from (value between 0 and 255)
  2249. * @param b defines the blue component to read from (value between 0 and 255)
  2250. * @param a defines the alpha component to read from (value between 0 and 255)
  2251. * @returns a new Color3 object
  2252. */
  2253. Color4.FromInts = function (r, g, b, a) {
  2254. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2255. };
  2256. /**
  2257. * Check the content of a given array and convert it to an array containing RGBA data
  2258. * If the original array was already containing count * 4 values then it is returned directly
  2259. * @param colors defines the array to check
  2260. * @param count defines the number of RGBA data to expect
  2261. * @returns an array containing count * 4 values (RGBA)
  2262. */
  2263. Color4.CheckColors4 = function (colors, count) {
  2264. // Check if color3 was used
  2265. if (colors.length === count * 3) {
  2266. var colors4 = [];
  2267. for (var index = 0; index < colors.length; index += 3) {
  2268. var newIndex = (index / 3) * 4;
  2269. colors4[newIndex] = colors[index];
  2270. colors4[newIndex + 1] = colors[index + 1];
  2271. colors4[newIndex + 2] = colors[index + 2];
  2272. colors4[newIndex + 3] = 1.0;
  2273. }
  2274. return colors4;
  2275. }
  2276. return colors;
  2277. };
  2278. return Color4;
  2279. }());
  2280. BABYLON.Color4 = Color4;
  2281. var Vector2 = /** @class */ (function () {
  2282. /**
  2283. * Creates a new Vector2 from the passed x and y coordinates.
  2284. */
  2285. function Vector2(x, y) {
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Returns a string with the Vector2 coordinates.
  2291. */
  2292. Vector2.prototype.toString = function () {
  2293. return "{X: " + this.x + " Y:" + this.y + "}";
  2294. };
  2295. /**
  2296. * Returns the string "Vector2"
  2297. */
  2298. Vector2.prototype.getClassName = function () {
  2299. return "Vector2";
  2300. };
  2301. /**
  2302. * Returns the Vector2 hash code as a number.
  2303. */
  2304. Vector2.prototype.getHashCode = function () {
  2305. var hash = this.x || 0;
  2306. hash = (hash * 397) ^ (this.y || 0);
  2307. return hash;
  2308. };
  2309. // Operators
  2310. /**
  2311. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2312. * Returns the Vector2.
  2313. */
  2314. Vector2.prototype.toArray = function (array, index) {
  2315. if (index === void 0) { index = 0; }
  2316. array[index] = this.x;
  2317. array[index + 1] = this.y;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new array with 2 elements : the Vector2 coordinates.
  2322. */
  2323. Vector2.prototype.asArray = function () {
  2324. var result = new Array();
  2325. this.toArray(result, 0);
  2326. return result;
  2327. };
  2328. /**
  2329. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2330. * Returns the updated Vector2.
  2331. */
  2332. Vector2.prototype.copyFrom = function (source) {
  2333. this.x = source.x;
  2334. this.y = source.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Sets the Vector2 coordinates with the passed floats.
  2339. * Returns the updated Vector2.
  2340. */
  2341. Vector2.prototype.copyFromFloats = function (x, y) {
  2342. this.x = x;
  2343. this.y = y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the passed floats.
  2348. * Returns the updated Vector2.
  2349. */
  2350. Vector2.prototype.set = function (x, y) {
  2351. return this.copyFromFloats(x, y);
  2352. };
  2353. /**
  2354. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2355. */
  2356. Vector2.prototype.add = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2361. * Returns the Vector2.
  2362. */
  2363. Vector2.prototype.addToRef = function (otherVector, result) {
  2364. result.x = this.x + otherVector.x;
  2365. result.y = this.y + otherVector.y;
  2366. return this;
  2367. };
  2368. /**
  2369. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2370. * Returns the updated Vector2.
  2371. */
  2372. Vector2.prototype.addInPlace = function (otherVector) {
  2373. this.x += otherVector.x;
  2374. this.y += otherVector.y;
  2375. return this;
  2376. };
  2377. /**
  2378. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2379. */
  2380. Vector2.prototype.addVector3 = function (otherVector) {
  2381. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2382. };
  2383. /**
  2384. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2385. */
  2386. Vector2.prototype.subtract = function (otherVector) {
  2387. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2388. };
  2389. /**
  2390. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2391. * Returns the Vector2.
  2392. */
  2393. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2394. result.x = this.x - otherVector.x;
  2395. result.y = this.y - otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2400. * Returns the updated Vector2.
  2401. */
  2402. Vector2.prototype.subtractInPlace = function (otherVector) {
  2403. this.x -= otherVector.x;
  2404. this.y -= otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2409. * Returns the updated Vector2.
  2410. */
  2411. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2412. this.x *= otherVector.x;
  2413. this.y *= otherVector.y;
  2414. return this;
  2415. };
  2416. /**
  2417. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2418. */
  2419. Vector2.prototype.multiply = function (otherVector) {
  2420. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2421. };
  2422. /**
  2423. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2424. * Returns the Vector2.
  2425. */
  2426. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2427. result.x = this.x * otherVector.x;
  2428. result.y = this.y * otherVector.y;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2433. */
  2434. Vector2.prototype.multiplyByFloats = function (x, y) {
  2435. return new Vector2(this.x * x, this.y * y);
  2436. };
  2437. /**
  2438. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2439. */
  2440. Vector2.prototype.divide = function (otherVector) {
  2441. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2442. };
  2443. /**
  2444. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2445. * Returns the Vector2.
  2446. */
  2447. Vector2.prototype.divideToRef = function (otherVector, result) {
  2448. result.x = this.x / otherVector.x;
  2449. result.y = this.y / otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Divides the current Vector3 coordinates by the passed ones.
  2454. * Returns the updated Vector3.
  2455. */
  2456. Vector2.prototype.divideInPlace = function (otherVector) {
  2457. return this.divideToRef(otherVector, this);
  2458. };
  2459. /**
  2460. * Returns a new Vector2 with current Vector2 negated coordinates.
  2461. */
  2462. Vector2.prototype.negate = function () {
  2463. return new Vector2(-this.x, -this.y);
  2464. };
  2465. /**
  2466. * Multiply the Vector2 coordinates by scale.
  2467. * Returns the updated Vector2.
  2468. */
  2469. Vector2.prototype.scaleInPlace = function (scale) {
  2470. this.x *= scale;
  2471. this.y *= scale;
  2472. return this;
  2473. };
  2474. /**
  2475. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2476. */
  2477. Vector2.prototype.scale = function (scale) {
  2478. var result = new Vector2(0, 0);
  2479. this.scaleToRef(scale, result);
  2480. return result;
  2481. };
  2482. /**
  2483. * Scale the current Vector2 values by a factor to a given Vector2
  2484. * @param scale defines the scale factor
  2485. * @param result defines the Vector2 object where to store the result
  2486. * @returns the unmodified current Vector2
  2487. */
  2488. Vector2.prototype.scaleToRef = function (scale, result) {
  2489. result.x = this.x * scale;
  2490. result.y = this.y * scale;
  2491. return this;
  2492. };
  2493. /**
  2494. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2495. * @param scale defines the scale factor
  2496. * @param result defines the Vector2 object where to store the result
  2497. * @returns the unmodified current Vector2
  2498. */
  2499. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2500. result.x += this.x * scale;
  2501. result.y += this.y * scale;
  2502. return this;
  2503. };
  2504. /**
  2505. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2512. */
  2513. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2514. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2515. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2516. };
  2517. // Properties
  2518. /**
  2519. * Returns the vector length (float).
  2520. */
  2521. Vector2.prototype.length = function () {
  2522. return Math.sqrt(this.x * this.x + this.y * this.y);
  2523. };
  2524. /**
  2525. * Returns the vector squared length (float);
  2526. */
  2527. Vector2.prototype.lengthSquared = function () {
  2528. return (this.x * this.x + this.y * this.y);
  2529. };
  2530. // Methods
  2531. /**
  2532. * Normalize the vector.
  2533. * Returns the updated Vector2.
  2534. */
  2535. Vector2.prototype.normalize = function () {
  2536. var len = this.length();
  2537. if (len === 0)
  2538. return this;
  2539. var num = 1.0 / len;
  2540. this.x *= num;
  2541. this.y *= num;
  2542. return this;
  2543. };
  2544. /**
  2545. * Returns a new Vector2 copied from the Vector2.
  2546. */
  2547. Vector2.prototype.clone = function () {
  2548. return new Vector2(this.x, this.y);
  2549. };
  2550. // Statics
  2551. /**
  2552. * Returns a new Vector2(0, 0)
  2553. */
  2554. Vector2.Zero = function () {
  2555. return new Vector2(0, 0);
  2556. };
  2557. /**
  2558. * Returns a new Vector2(1, 1)
  2559. */
  2560. Vector2.One = function () {
  2561. return new Vector2(1, 1);
  2562. };
  2563. /**
  2564. * Returns a new Vector2 set from the passed index element of the passed array.
  2565. */
  2566. Vector2.FromArray = function (array, offset) {
  2567. if (offset === void 0) { offset = 0; }
  2568. return new Vector2(array[offset], array[offset + 1]);
  2569. };
  2570. /**
  2571. * Sets "result" from the passed index element of the passed array.
  2572. */
  2573. Vector2.FromArrayToRef = function (array, offset, result) {
  2574. result.x = array[offset];
  2575. result.y = array[offset + 1];
  2576. };
  2577. /**
  2578. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2579. */
  2580. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2581. var squared = amount * amount;
  2582. var cubed = amount * squared;
  2583. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2584. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2585. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2586. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2587. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2588. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2589. return new Vector2(x, y);
  2590. };
  2591. /**
  2592. * 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".
  2593. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2594. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2595. */
  2596. Vector2.Clamp = function (value, min, max) {
  2597. var x = value.x;
  2598. x = (x > max.x) ? max.x : x;
  2599. x = (x < min.x) ? min.x : x;
  2600. var y = value.y;
  2601. y = (y > max.y) ? max.y : y;
  2602. y = (y < min.y) ? min.y : y;
  2603. return new Vector2(x, y);
  2604. };
  2605. /**
  2606. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2607. */
  2608. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2609. var squared = amount * amount;
  2610. var cubed = amount * squared;
  2611. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2612. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2613. var part3 = (cubed - (2.0 * squared)) + amount;
  2614. var part4 = cubed - squared;
  2615. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2616. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2621. */
  2622. Vector2.Lerp = function (start, end, amount) {
  2623. var x = start.x + ((end.x - start.x) * amount);
  2624. var y = start.y + ((end.y - start.y) * amount);
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns the dot product (float) of the vector "left" and the vector "right".
  2629. */
  2630. Vector2.Dot = function (left, right) {
  2631. return left.x * right.x + left.y * right.y;
  2632. };
  2633. /**
  2634. * Returns a new Vector2 equal to the normalized passed vector.
  2635. */
  2636. Vector2.Normalize = function (vector) {
  2637. var newVector = vector.clone();
  2638. newVector.normalize();
  2639. return newVector;
  2640. };
  2641. /**
  2642. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2643. */
  2644. Vector2.Minimize = function (left, right) {
  2645. var x = (left.x < right.x) ? left.x : right.x;
  2646. var y = (left.y < right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2651. */
  2652. Vector2.Maximize = function (left, right) {
  2653. var x = (left.x > right.x) ? left.x : right.x;
  2654. var y = (left.y > right.y) ? left.y : right.y;
  2655. return new Vector2(x, y);
  2656. };
  2657. /**
  2658. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2659. */
  2660. Vector2.Transform = function (vector, transformation) {
  2661. var r = Vector2.Zero();
  2662. Vector2.TransformToRef(vector, transformation, r);
  2663. return r;
  2664. };
  2665. /**
  2666. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2667. */
  2668. Vector2.TransformToRef = function (vector, transformation, result) {
  2669. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2670. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2671. result.x = x;
  2672. result.y = y;
  2673. };
  2674. /**
  2675. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2676. */
  2677. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2678. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2679. var sign = a < 0 ? -1 : 1;
  2680. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2681. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2682. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2683. };
  2684. /**
  2685. * Returns the distance (float) between the vectors "value1" and "value2".
  2686. */
  2687. Vector2.Distance = function (value1, value2) {
  2688. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2689. };
  2690. /**
  2691. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2692. */
  2693. Vector2.DistanceSquared = function (value1, value2) {
  2694. var x = value1.x - value2.x;
  2695. var y = value1.y - value2.y;
  2696. return (x * x) + (y * y);
  2697. };
  2698. /**
  2699. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2700. */
  2701. Vector2.Center = function (value1, value2) {
  2702. var center = value1.add(value2);
  2703. center.scaleInPlace(0.5);
  2704. return center;
  2705. };
  2706. /**
  2707. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2708. */
  2709. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2710. var l2 = Vector2.DistanceSquared(segA, segB);
  2711. if (l2 === 0.0) {
  2712. return Vector2.Distance(p, segA);
  2713. }
  2714. var v = segB.subtract(segA);
  2715. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2716. var proj = segA.add(v.multiplyByFloats(t, t));
  2717. return Vector2.Distance(p, proj);
  2718. };
  2719. return Vector2;
  2720. }());
  2721. BABYLON.Vector2 = Vector2;
  2722. /**
  2723. * Classed used to store (x,y,z) vector representation
  2724. * A Vector3 is the main object used in 3D geometry
  2725. * It can represent etiher the coordinates of a point the space, either a direction
  2726. * Reminder: Babylon.js uses a left handed forward facing system
  2727. */
  2728. var Vector3 = /** @class */ (function () {
  2729. /**
  2730. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2731. * @param x defines the first coordinates (on X axis)
  2732. * @param y defines the second coordinates (on Y axis)
  2733. * @param z defines the third coordinates (on Z axis)
  2734. */
  2735. function Vector3(
  2736. /**
  2737. * Defines the first coordinates (on X axis)
  2738. */
  2739. x,
  2740. /**
  2741. * Defines the second coordinates (on Y axis)
  2742. */
  2743. y,
  2744. /**
  2745. * Defines the third coordinates (on Z axis)
  2746. */
  2747. z) {
  2748. this.x = x;
  2749. this.y = y;
  2750. this.z = z;
  2751. }
  2752. /**
  2753. * Creates a string representation of the Vector3
  2754. * @returns a string with the Vector3 coordinates.
  2755. */
  2756. Vector3.prototype.toString = function () {
  2757. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2758. };
  2759. /**
  2760. * Gets the class name
  2761. * @returns the string "Vector3"
  2762. */
  2763. Vector3.prototype.getClassName = function () {
  2764. return "Vector3";
  2765. };
  2766. /**
  2767. * Creates the Vector3 hash code
  2768. * @returns a number which tends to be unique between Vector3 instances
  2769. */
  2770. Vector3.prototype.getHashCode = function () {
  2771. var hash = this.x || 0;
  2772. hash = (hash * 397) ^ (this.y || 0);
  2773. hash = (hash * 397) ^ (this.z || 0);
  2774. return hash;
  2775. };
  2776. // Operators
  2777. /**
  2778. * Creates an array containing three elements : the coordinates of the Vector3
  2779. * @returns a new array of numbers
  2780. */
  2781. Vector3.prototype.asArray = function () {
  2782. var result = [];
  2783. this.toArray(result, 0);
  2784. return result;
  2785. };
  2786. /**
  2787. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2788. * @param array defines the destination array
  2789. * @param index defines the offset in the destination array
  2790. * @returns the current Vector3
  2791. */
  2792. Vector3.prototype.toArray = function (array, index) {
  2793. if (index === void 0) { index = 0; }
  2794. array[index] = this.x;
  2795. array[index + 1] = this.y;
  2796. array[index + 2] = this.z;
  2797. return this;
  2798. };
  2799. /**
  2800. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2801. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2802. */
  2803. Vector3.prototype.toQuaternion = function () {
  2804. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2805. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2806. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2807. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2808. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2809. var cosy = Math.cos(this.y * 0.5);
  2810. var siny = Math.sin(this.y * 0.5);
  2811. result.x = coszMinusx * siny;
  2812. result.y = -sinzMinusx * siny;
  2813. result.z = sinxPlusz * cosy;
  2814. result.w = cosxPlusz * cosy;
  2815. return result;
  2816. };
  2817. /**
  2818. * Adds the passed vector to the current Vector3
  2819. * @param otherVector defines the second operand
  2820. * @returns the current updated Vector3
  2821. */
  2822. Vector3.prototype.addInPlace = function (otherVector) {
  2823. this.x += otherVector.x;
  2824. this.y += otherVector.y;
  2825. this.z += otherVector.z;
  2826. return this;
  2827. };
  2828. /**
  2829. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2830. * @param otherVector defines the second operand
  2831. * @returns the resulting Vector3
  2832. */
  2833. Vector3.prototype.add = function (otherVector) {
  2834. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2835. };
  2836. /**
  2837. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2838. * @param otherVector defines the second operand
  2839. * @param result defines the Vector3 object where to store the result
  2840. * @returns the current Vector3
  2841. */
  2842. Vector3.prototype.addToRef = function (otherVector, result) {
  2843. result.x = this.x + otherVector.x;
  2844. result.y = this.y + otherVector.y;
  2845. result.z = this.z + otherVector.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Subtract the passed vector from the current Vector3
  2850. * @param otherVector defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.subtractInPlace = function (otherVector) {
  2854. this.x -= otherVector.x;
  2855. this.y -= otherVector.y;
  2856. this.z -= otherVector.z;
  2857. return this;
  2858. };
  2859. /**
  2860. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2861. * @param otherVector defines the second operand
  2862. * @returns the resulting Vector3
  2863. */
  2864. Vector3.prototype.subtract = function (otherVector) {
  2865. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2866. };
  2867. /**
  2868. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2869. * @param otherVector defines the second operand
  2870. * @param result defines the Vector3 object where to store the result
  2871. * @returns the current Vector3
  2872. */
  2873. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2874. result.x = this.x - otherVector.x;
  2875. result.y = this.y - otherVector.y;
  2876. result.z = this.z - otherVector.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2881. * @param x defines the x coordinate of the operand
  2882. * @param y defines the y coordinate of the operand
  2883. * @param z defines the z coordinate of the operand
  2884. * @returns the resulting Vector3
  2885. */
  2886. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2887. return new Vector3(this.x - x, this.y - y, this.z - z);
  2888. };
  2889. /**
  2890. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2891. * @param x defines the x coordinate of the operand
  2892. * @param y defines the y coordinate of the operand
  2893. * @param z defines the z coordinate of the operand
  2894. * @param result defines the Vector3 object where to store the result
  2895. * @returns the current Vector3
  2896. */
  2897. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2898. result.x = this.x - x;
  2899. result.y = this.y - y;
  2900. result.z = this.z - z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2905. * @returns a new Vector3
  2906. */
  2907. Vector3.prototype.negate = function () {
  2908. return new Vector3(-this.x, -this.y, -this.z);
  2909. };
  2910. /**
  2911. * Multiplies the Vector3 coordinates by the float "scale"
  2912. * @param scale defines the multiplier factor
  2913. * @returns the current updated Vector3
  2914. */
  2915. Vector3.prototype.scaleInPlace = function (scale) {
  2916. this.x *= scale;
  2917. this.y *= scale;
  2918. this.z *= scale;
  2919. return this;
  2920. };
  2921. /**
  2922. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2923. * @param scale defines the multiplier factor
  2924. * @returns a new Vector3
  2925. */
  2926. Vector3.prototype.scale = function (scale) {
  2927. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2928. };
  2929. /**
  2930. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2931. * @param scale defines the multiplier factor
  2932. * @param result defines the Vector3 object where to store the result
  2933. * @returns the current Vector3
  2934. */
  2935. Vector3.prototype.scaleToRef = function (scale, result) {
  2936. result.x = this.x * scale;
  2937. result.y = this.y * scale;
  2938. result.z = this.z * scale;
  2939. return this;
  2940. };
  2941. /**
  2942. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2943. * @param scale defines the scale factor
  2944. * @param result defines the Vector3 object where to store the result
  2945. * @returns the unmodified current Vector3
  2946. */
  2947. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2948. result.x += this.x * scale;
  2949. result.y += this.y * scale;
  2950. result.z += this.z * scale;
  2951. return this;
  2952. };
  2953. /**
  2954. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2955. * @param otherVector defines the second operand
  2956. * @returns true if both vectors are equals
  2957. */
  2958. Vector3.prototype.equals = function (otherVector) {
  2959. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2963. * @param otherVector defines the second operand
  2964. * @param epsilon defines the minimal distance to define values as equals
  2965. * @returns true if both vectors are distant less than epsilon
  2966. */
  2967. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2968. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2969. 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);
  2970. };
  2971. /**
  2972. * Returns true if the current Vector3 coordinates equals the passed floats
  2973. * @param x defines the x coordinate of the operand
  2974. * @param y defines the y coordinate of the operand
  2975. * @param z defines the z coordinate of the operand
  2976. * @returns true if both vectors are equals
  2977. */
  2978. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2979. return this.x === x && this.y === y && this.z === z;
  2980. };
  2981. /**
  2982. * Multiplies the current Vector3 coordinates by the passed ones
  2983. * @param otherVector defines the second operand
  2984. * @returns the current updated Vector3
  2985. */
  2986. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2987. this.x *= otherVector.x;
  2988. this.y *= otherVector.y;
  2989. this.z *= otherVector.z;
  2990. return this;
  2991. };
  2992. /**
  2993. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2994. * @param otherVector defines the second operand
  2995. * @returns the new Vector3
  2996. */
  2997. Vector3.prototype.multiply = function (otherVector) {
  2998. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2999. };
  3000. /**
  3001. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  3002. * @param otherVector defines the second operand
  3003. * @param result defines the Vector3 object where to store the result
  3004. * @returns the current Vector3
  3005. */
  3006. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3007. result.x = this.x * otherVector.x;
  3008. result.y = this.y * otherVector.y;
  3009. result.z = this.z * otherVector.z;
  3010. return this;
  3011. };
  3012. /**
  3013. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3014. * @param x defines the x coordinate of the operand
  3015. * @param y defines the y coordinate of the operand
  3016. * @param z defines the z coordinate of the operand
  3017. * @returns the new Vector3
  3018. */
  3019. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3020. return new Vector3(this.x * x, this.y * y, this.z * z);
  3021. };
  3022. /**
  3023. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3024. * @param otherVector defines the second operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.divide = function (otherVector) {
  3028. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3029. };
  3030. /**
  3031. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3032. * @param otherVector defines the second operand
  3033. * @param result defines the Vector3 object where to store the result
  3034. * @returns the current Vector3
  3035. */
  3036. Vector3.prototype.divideToRef = function (otherVector, result) {
  3037. result.x = this.x / otherVector.x;
  3038. result.y = this.y / otherVector.y;
  3039. result.z = this.z / otherVector.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Divides the current Vector3 coordinates by the passed ones.
  3044. * @param otherVector defines the second operand
  3045. * @returns the current updated Vector3
  3046. */
  3047. Vector3.prototype.divideInPlace = function (otherVector) {
  3048. return this.divideToRef(otherVector, this);
  3049. };
  3050. /**
  3051. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3052. * @param other defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.minimizeInPlace = function (other) {
  3056. if (other.x < this.x)
  3057. this.x = other.x;
  3058. if (other.y < this.y)
  3059. this.y = other.y;
  3060. if (other.z < this.z)
  3061. this.z = other.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3066. * @param other defines the second operand
  3067. * @returns the current updated Vector3
  3068. */
  3069. Vector3.prototype.maximizeInPlace = function (other) {
  3070. if (other.x > this.x)
  3071. this.x = other.x;
  3072. if (other.y > this.y)
  3073. this.y = other.y;
  3074. if (other.z > this.z)
  3075. this.z = other.z;
  3076. return this;
  3077. };
  3078. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3079. /**
  3080. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3081. */
  3082. get: function () {
  3083. var absX = Math.abs(this.x);
  3084. var absY = Math.abs(this.y);
  3085. if (absX !== absY) {
  3086. return true;
  3087. }
  3088. var absZ = Math.abs(this.z);
  3089. if (absX !== absZ) {
  3090. return true;
  3091. }
  3092. if (absY !== absZ) {
  3093. return true;
  3094. }
  3095. return false;
  3096. },
  3097. enumerable: true,
  3098. configurable: true
  3099. });
  3100. // Properties
  3101. /**
  3102. * Gets the length of the Vector3
  3103. * @returns the length of the Vecto3
  3104. */
  3105. Vector3.prototype.length = function () {
  3106. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3107. };
  3108. /**
  3109. * Gets the squared length of the Vector3
  3110. * @returns squared length of the Vector3
  3111. */
  3112. Vector3.prototype.lengthSquared = function () {
  3113. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3114. };
  3115. /**
  3116. * Normalize the current Vector3.
  3117. * Please note that this is an in place operation.
  3118. * @returns the current updated Vector3
  3119. */
  3120. Vector3.prototype.normalize = function () {
  3121. var len = this.length();
  3122. if (len === 0 || len === 1.0)
  3123. return this;
  3124. var num = 1.0 / len;
  3125. this.x *= num;
  3126. this.y *= num;
  3127. this.z *= num;
  3128. return this;
  3129. };
  3130. /**
  3131. * Normalize the current Vector3 to a new vector
  3132. * @returns the new Vector3
  3133. */
  3134. Vector3.prototype.normalizeToNew = function () {
  3135. var normalized = new Vector3(0, 0, 0);
  3136. this.normalizeToRef(normalized);
  3137. return normalized;
  3138. };
  3139. /**
  3140. * Normalize the current Vector3 to the reference
  3141. * @param reference define the Vector3 to update
  3142. * @returns the updated Vector3
  3143. */
  3144. Vector3.prototype.normalizeToRef = function (reference) {
  3145. var len = this.length();
  3146. if (len === 0 || len === 1.0) {
  3147. reference.set(this.x, this.y, this.z);
  3148. return reference;
  3149. }
  3150. var scale = 1.0 / len;
  3151. this.scaleToRef(scale, reference);
  3152. return reference;
  3153. };
  3154. /**
  3155. * Creates a new Vector3 copied from the current Vector3
  3156. * @returns the new Vector3
  3157. */
  3158. Vector3.prototype.clone = function () {
  3159. return new Vector3(this.x, this.y, this.z);
  3160. };
  3161. /**
  3162. * Copies the passed vector coordinates to the current Vector3 ones
  3163. * @param source defines the source Vector3
  3164. * @returns the current updated Vector3
  3165. */
  3166. Vector3.prototype.copyFrom = function (source) {
  3167. this.x = source.x;
  3168. this.y = source.y;
  3169. this.z = source.z;
  3170. return this;
  3171. };
  3172. /**
  3173. * Copies the passed floats to the current Vector3 coordinates
  3174. * @param x defines the x coordinate of the operand
  3175. * @param y defines the y coordinate of the operand
  3176. * @param z defines the z coordinate of the operand
  3177. * @returns the current updated Vector3
  3178. */
  3179. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3180. this.x = x;
  3181. this.y = y;
  3182. this.z = z;
  3183. return this;
  3184. };
  3185. /**
  3186. * Copies the passed floats to the current Vector3 coordinates
  3187. * @param x defines the x coordinate of the operand
  3188. * @param y defines the y coordinate of the operand
  3189. * @param z defines the z coordinate of the operand
  3190. * @returns the current updated Vector3
  3191. */
  3192. Vector3.prototype.set = function (x, y, z) {
  3193. return this.copyFromFloats(x, y, z);
  3194. };
  3195. // Statics
  3196. /**
  3197. * Get the clip factor between two vectors
  3198. * @param vector0 defines the first operand
  3199. * @param vector1 defines the second operand
  3200. * @param axis defines the axis to use
  3201. * @param size defines the size along the axis
  3202. * @returns the clip factor
  3203. */
  3204. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3205. var d0 = Vector3.Dot(vector0, axis) - size;
  3206. var d1 = Vector3.Dot(vector1, axis) - size;
  3207. var s = d0 / (d0 - d1);
  3208. return s;
  3209. };
  3210. /**
  3211. * Get angle between two vectors
  3212. * @param vector0 angle between vector0 and vector1
  3213. * @param vector1 angle between vector0 and vector1
  3214. * @param normal direction of the normal
  3215. * @return the angle between vector0 and vector1
  3216. */
  3217. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3218. var v0 = vector0.clone().normalize();
  3219. var v1 = vector1.clone().normalize();
  3220. var dot = Vector3.Dot(v0, v1);
  3221. var n = Vector3.Cross(v0, v1);
  3222. if (Vector3.Dot(n, normal) > 0) {
  3223. return Math.acos(dot);
  3224. }
  3225. return -Math.acos(dot);
  3226. };
  3227. /**
  3228. * Returns a new Vector3 set from the index "offset" of the passed array
  3229. * @param array defines the source array
  3230. * @param offset defines the offset in the source array
  3231. * @returns the new Vector3
  3232. */
  3233. Vector3.FromArray = function (array, offset) {
  3234. if (!offset) {
  3235. offset = 0;
  3236. }
  3237. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3241. * This function is deprecated. Use FromArray instead
  3242. * @param array defines the source array
  3243. * @param offset defines the offset in the source array
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.FromFloatArray = function (array, offset) {
  3247. return Vector3.FromArray(array, offset);
  3248. };
  3249. /**
  3250. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3251. * @param array defines the source array
  3252. * @param offset defines the offset in the source array
  3253. * @param result defines the Vector3 where to store the result
  3254. */
  3255. Vector3.FromArrayToRef = function (array, offset, result) {
  3256. result.x = array[offset];
  3257. result.y = array[offset + 1];
  3258. result.z = array[offset + 2];
  3259. };
  3260. /**
  3261. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3262. * This function is deprecated. Use FromArrayToRef instead.
  3263. * @param array defines the source array
  3264. * @param offset defines the offset in the source array
  3265. * @param result defines the Vector3 where to store the result
  3266. */
  3267. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3268. return Vector3.FromArrayToRef(array, offset, result);
  3269. };
  3270. /**
  3271. * Sets the passed vector "result" with the passed floats.
  3272. * @param x defines the x coordinate of the source
  3273. * @param y defines the y coordinate of the source
  3274. * @param z defines the z coordinate of the source
  3275. * @param result defines the Vector3 where to store the result
  3276. */
  3277. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3278. result.x = x;
  3279. result.y = y;
  3280. result.z = z;
  3281. };
  3282. /**
  3283. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3284. * @returns a new empty Vector3
  3285. */
  3286. Vector3.Zero = function () {
  3287. return new Vector3(0.0, 0.0, 0.0);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3291. * @returns a new unit Vector3
  3292. */
  3293. Vector3.One = function () {
  3294. return new Vector3(1.0, 1.0, 1.0);
  3295. };
  3296. /**
  3297. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3298. * @returns a new up Vector3
  3299. */
  3300. Vector3.Up = function () {
  3301. return new Vector3(0.0, 1.0, 0.0);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3305. * @returns a new forward Vector3
  3306. */
  3307. Vector3.Forward = function () {
  3308. return new Vector3(0.0, 0.0, 1.0);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3312. * @returns a new right Vector3
  3313. */
  3314. Vector3.Right = function () {
  3315. return new Vector3(1.0, 0.0, 0.0);
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3319. * @returns a new left Vector3
  3320. */
  3321. Vector3.Left = function () {
  3322. return new Vector3(-1.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3326. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3327. * @param vector defines the Vector3 to transform
  3328. * @param transformation defines the transformation matrix
  3329. * @returns the transformed Vector3
  3330. */
  3331. Vector3.TransformCoordinates = function (vector, transformation) {
  3332. var result = Vector3.Zero();
  3333. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3334. return result;
  3335. };
  3336. /**
  3337. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3338. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3339. * @param vector defines the Vector3 to transform
  3340. * @param transformation defines the transformation matrix
  3341. * @param result defines the Vector3 where to store the result
  3342. */
  3343. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3344. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3345. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3346. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3347. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3348. result.x = x / w;
  3349. result.y = y / w;
  3350. result.z = z / w;
  3351. };
  3352. /**
  3353. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3354. * This method computes tranformed coordinates only, not transformed direction vectors
  3355. * @param x define the x coordinate of the source vector
  3356. * @param y define the y coordinate of the source vector
  3357. * @param z define the z coordinate of the source vector
  3358. * @param transformation defines the transformation matrix
  3359. * @param result defines the Vector3 where to store the result
  3360. */
  3361. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3362. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3363. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3364. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3365. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3366. result.x = rx / rw;
  3367. result.y = ry / rw;
  3368. result.z = rz / rw;
  3369. };
  3370. /**
  3371. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3372. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3373. * @param vector defines the Vector3 to transform
  3374. * @param transformation defines the transformation matrix
  3375. * @returns the new Vector3
  3376. */
  3377. Vector3.TransformNormal = function (vector, transformation) {
  3378. var result = Vector3.Zero();
  3379. Vector3.TransformNormalToRef(vector, transformation, result);
  3380. return result;
  3381. };
  3382. /**
  3383. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3384. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3385. * @param vector defines the Vector3 to transform
  3386. * @param transformation defines the transformation matrix
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3390. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3391. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3392. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3393. result.x = x;
  3394. result.y = y;
  3395. result.z = z;
  3396. };
  3397. /**
  3398. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param x define the x coordinate of the source vector
  3401. * @param y define the y coordinate of the source vector
  3402. * @param z define the z coordinate of the source vector
  3403. * @param transformation defines the transformation matrix
  3404. * @param result defines the Vector3 where to store the result
  3405. */
  3406. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3407. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3408. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3409. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3410. };
  3411. /**
  3412. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3413. * @param value1 defines the first control point
  3414. * @param value2 defines the second control point
  3415. * @param value3 defines the third control point
  3416. * @param value4 defines the fourth control point
  3417. * @param amount defines the amount on the spline to use
  3418. * @returns the new Vector3
  3419. */
  3420. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3421. var squared = amount * amount;
  3422. var cubed = amount * squared;
  3423. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3424. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3425. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3426. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3427. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3428. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3429. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3430. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3431. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3432. return new Vector3(x, y, z);
  3433. };
  3434. /**
  3435. * 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"
  3436. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3437. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3438. * @param value defines the current value
  3439. * @param min defines the lower range value
  3440. * @param max defines the upper range value
  3441. * @returns the new Vector3
  3442. */
  3443. Vector3.Clamp = function (value, min, max) {
  3444. var x = value.x;
  3445. x = (x > max.x) ? max.x : x;
  3446. x = (x < min.x) ? min.x : x;
  3447. var y = value.y;
  3448. y = (y > max.y) ? max.y : y;
  3449. y = (y < min.y) ? min.y : y;
  3450. var z = value.z;
  3451. z = (z > max.z) ? max.z : z;
  3452. z = (z < min.z) ? min.z : z;
  3453. return new Vector3(x, y, z);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3457. * @param value1 defines the first control point
  3458. * @param tangent1 defines the first tangent vector
  3459. * @param value2 defines the second control point
  3460. * @param tangent2 defines the second tangent vector
  3461. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3462. * @returns the new Vector3
  3463. */
  3464. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3465. var squared = amount * amount;
  3466. var cubed = amount * squared;
  3467. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3468. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3469. var part3 = (cubed - (2.0 * squared)) + amount;
  3470. var part4 = cubed - squared;
  3471. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3472. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3473. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3474. return new Vector3(x, y, z);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3478. * @param start defines the start value
  3479. * @param end defines the end value
  3480. * @param amount max defines amount between both (between 0 and 1)
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Lerp = function (start, end, amount) {
  3484. var result = new Vector3(0, 0, 0);
  3485. Vector3.LerpToRef(start, end, amount, result);
  3486. return result;
  3487. };
  3488. /**
  3489. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3490. * @param start defines the start value
  3491. * @param end defines the end value
  3492. * @param amount max defines amount between both (between 0 and 1)
  3493. * @param result defines the Vector3 where to store the result
  3494. */
  3495. Vector3.LerpToRef = function (start, end, amount, result) {
  3496. result.x = start.x + ((end.x - start.x) * amount);
  3497. result.y = start.y + ((end.y - start.y) * amount);
  3498. result.z = start.z + ((end.z - start.z) * amount);
  3499. };
  3500. /**
  3501. * Returns the dot product (float) between the vectors "left" and "right"
  3502. * @param left defines the left operand
  3503. * @param right defines the right operand
  3504. * @returns the dot product
  3505. */
  3506. Vector3.Dot = function (left, right) {
  3507. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3508. };
  3509. /**
  3510. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3511. * The cross product is then orthogonal to both "left" and "right"
  3512. * @param left defines the left operand
  3513. * @param right defines the right operand
  3514. * @returns the cross product
  3515. */
  3516. Vector3.Cross = function (left, right) {
  3517. var result = Vector3.Zero();
  3518. Vector3.CrossToRef(left, right, result);
  3519. return result;
  3520. };
  3521. /**
  3522. * Sets the passed vector "result" with the cross product of "left" and "right"
  3523. * The cross product is then orthogonal to both "left" and "right"
  3524. * @param left defines the left operand
  3525. * @param right defines the right operand
  3526. * @param result defines the Vector3 where to store the result
  3527. */
  3528. Vector3.CrossToRef = function (left, right, result) {
  3529. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3530. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3531. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3532. result.copyFrom(MathTmp.Vector3[0]);
  3533. };
  3534. /**
  3535. * Returns a new Vector3 as the normalization of the passed vector
  3536. * @param vector defines the Vector3 to normalize
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Normalize = function (vector) {
  3540. var result = Vector3.Zero();
  3541. Vector3.NormalizeToRef(vector, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed vector "result" with the normalization of the passed first vector
  3546. * @param vector defines the Vector3 to normalize
  3547. * @param result defines the Vector3 where to store the result
  3548. */
  3549. Vector3.NormalizeToRef = function (vector, result) {
  3550. result.copyFrom(vector);
  3551. result.normalize();
  3552. };
  3553. /**
  3554. * Project a Vector3 onto screen space
  3555. * @param vector defines the Vector3 to project
  3556. * @param world defines the world matrix to use
  3557. * @param transform defines the transform (view x projection) matrix to use
  3558. * @param viewport defines the screen viewport to use
  3559. * @returns the new Vector3
  3560. */
  3561. Vector3.Project = function (vector, world, transform, viewport) {
  3562. var cw = viewport.width;
  3563. var ch = viewport.height;
  3564. var cx = viewport.x;
  3565. var cy = viewport.y;
  3566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3567. 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);
  3568. var matrix = MathTmp.Matrix[0];
  3569. world.multiplyToRef(transform, matrix);
  3570. matrix.multiplyToRef(viewportMatrix, matrix);
  3571. return Vector3.TransformCoordinates(vector, matrix);
  3572. };
  3573. /**
  3574. * Unproject from screen space to object space
  3575. * @param source defines the screen space Vector3 to use
  3576. * @param viewportWidth defines the current width of the viewport
  3577. * @param viewportHeight defines the current height of the viewport
  3578. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3579. * @param transform defines the transform (view x projection) matrix to use
  3580. * @returns the new Vector3
  3581. */
  3582. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.invert();
  3586. source.x = source.x / viewportWidth * 2 - 1;
  3587. source.y = -(source.y / viewportHeight * 2 - 1);
  3588. var vector = Vector3.TransformCoordinates(source, matrix);
  3589. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3590. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3591. vector = vector.scale(1.0 / num);
  3592. }
  3593. return vector;
  3594. };
  3595. /**
  3596. * Unproject from screen space to object space
  3597. * @param source defines the screen space Vector3 to use
  3598. * @param viewportWidth defines the current width of the viewport
  3599. * @param viewportHeight defines the current height of the viewport
  3600. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3601. * @param view defines the view matrix to use
  3602. * @param projection defines the projection matrix to use
  3603. * @returns the new Vector3
  3604. */
  3605. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3606. var result = Vector3.Zero();
  3607. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3608. return result;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @param result defines the Vector3 where to store the result
  3619. */
  3620. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3621. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3622. };
  3623. /**
  3624. * Unproject from screen space to object space
  3625. * @param sourceX defines the screen space x coordinate to use
  3626. * @param sourceY defines the screen space y coordinate to use
  3627. * @param sourceZ defines the screen space z coordinate to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. var matrix = MathTmp.Matrix[0];
  3637. world.multiplyToRef(view, matrix);
  3638. matrix.multiplyToRef(projection, matrix);
  3639. matrix.invert();
  3640. var screenSource = MathTmp.Vector3[0];
  3641. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3642. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3643. screenSource.z = 2 * sourceZ - 1.0;
  3644. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3645. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3646. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3647. result.scaleInPlace(1.0 / num);
  3648. }
  3649. };
  3650. /**
  3651. * Gets the minimal coordinate values between two Vector3
  3652. * @param left defines the first operand
  3653. * @param right defines the second operand
  3654. * @returns the new Vector3
  3655. */
  3656. Vector3.Minimize = function (left, right) {
  3657. var min = left.clone();
  3658. min.minimizeInPlace(right);
  3659. return min;
  3660. };
  3661. /**
  3662. * Gets the maximal coordinate values between two Vector3
  3663. * @param left defines the first operand
  3664. * @param right defines the second operand
  3665. * @returns the new Vector3
  3666. */
  3667. Vector3.Maximize = function (left, right) {
  3668. var max = left.clone();
  3669. max.maximizeInPlace(right);
  3670. return max;
  3671. };
  3672. /**
  3673. * Returns the distance between the vectors "value1" and "value2"
  3674. * @param value1 defines the first operand
  3675. * @param value2 defines the second operand
  3676. * @returns the distance
  3677. */
  3678. Vector3.Distance = function (value1, value2) {
  3679. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3680. };
  3681. /**
  3682. * Returns the squared distance between the vectors "value1" and "value2"
  3683. * @param value1 defines the first operand
  3684. * @param value2 defines the second operand
  3685. * @returns the squared distance
  3686. */
  3687. Vector3.DistanceSquared = function (value1, value2) {
  3688. var x = value1.x - value2.x;
  3689. var y = value1.y - value2.y;
  3690. var z = value1.z - value2.z;
  3691. return (x * x) + (y * y) + (z * z);
  3692. };
  3693. /**
  3694. * Returns a new Vector3 located at the center between "value1" and "value2"
  3695. * @param value1 defines the first operand
  3696. * @param value2 defines the second operand
  3697. * @returns the new Vector3
  3698. */
  3699. Vector3.Center = function (value1, value2) {
  3700. var center = value1.add(value2);
  3701. center.scaleInPlace(0.5);
  3702. return center;
  3703. };
  3704. /**
  3705. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3706. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3707. * to something in order to rotate it from its local system to the given target system
  3708. * Note: axis1, axis2 and axis3 are normalized during this operation
  3709. * @param axis1 defines the first axis
  3710. * @param axis2 defines the second axis
  3711. * @param axis3 defines the third axis
  3712. * @returns a new Vector3
  3713. */
  3714. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3715. var rotation = Vector3.Zero();
  3716. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3717. return rotation;
  3718. };
  3719. /**
  3720. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3721. * @param axis1 defines the first axis
  3722. * @param axis2 defines the second axis
  3723. * @param axis3 defines the third axis
  3724. * @param ref defines the Vector3 where to store the result
  3725. */
  3726. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3727. var quat = MathTmp.Quaternion[0];
  3728. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3729. quat.toEulerAnglesToRef(ref);
  3730. };
  3731. return Vector3;
  3732. }());
  3733. BABYLON.Vector3 = Vector3;
  3734. //Vector4 class created for EulerAngle class conversion to Quaternion
  3735. var Vector4 = /** @class */ (function () {
  3736. /**
  3737. * Creates a Vector4 object from the passed floats.
  3738. */
  3739. function Vector4(x, y, z, w) {
  3740. this.x = x;
  3741. this.y = y;
  3742. this.z = z;
  3743. this.w = w;
  3744. }
  3745. /**
  3746. * Returns the string with the Vector4 coordinates.
  3747. */
  3748. Vector4.prototype.toString = function () {
  3749. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3750. };
  3751. /**
  3752. * Returns the string "Vector4".
  3753. */
  3754. Vector4.prototype.getClassName = function () {
  3755. return "Vector4";
  3756. };
  3757. /**
  3758. * Returns the Vector4 hash code.
  3759. */
  3760. Vector4.prototype.getHashCode = function () {
  3761. var hash = this.x || 0;
  3762. hash = (hash * 397) ^ (this.y || 0);
  3763. hash = (hash * 397) ^ (this.z || 0);
  3764. hash = (hash * 397) ^ (this.w || 0);
  3765. return hash;
  3766. };
  3767. // Operators
  3768. /**
  3769. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3770. */
  3771. Vector4.prototype.asArray = function () {
  3772. var result = new Array();
  3773. this.toArray(result, 0);
  3774. return result;
  3775. };
  3776. /**
  3777. * Populates the passed array from the passed index with the Vector4 coordinates.
  3778. * Returns the Vector4.
  3779. */
  3780. Vector4.prototype.toArray = function (array, index) {
  3781. if (index === undefined) {
  3782. index = 0;
  3783. }
  3784. array[index] = this.x;
  3785. array[index + 1] = this.y;
  3786. array[index + 2] = this.z;
  3787. array[index + 3] = this.w;
  3788. return this;
  3789. };
  3790. /**
  3791. * Adds the passed vector to the current Vector4.
  3792. * Returns the updated Vector4.
  3793. */
  3794. Vector4.prototype.addInPlace = function (otherVector) {
  3795. this.x += otherVector.x;
  3796. this.y += otherVector.y;
  3797. this.z += otherVector.z;
  3798. this.w += otherVector.w;
  3799. return this;
  3800. };
  3801. /**
  3802. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3803. */
  3804. Vector4.prototype.add = function (otherVector) {
  3805. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3806. };
  3807. /**
  3808. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3809. * Returns the current Vector4.
  3810. */
  3811. Vector4.prototype.addToRef = function (otherVector, result) {
  3812. result.x = this.x + otherVector.x;
  3813. result.y = this.y + otherVector.y;
  3814. result.z = this.z + otherVector.z;
  3815. result.w = this.w + otherVector.w;
  3816. return this;
  3817. };
  3818. /**
  3819. * Subtract in place the passed vector from the current Vector4.
  3820. * Returns the updated Vector4.
  3821. */
  3822. Vector4.prototype.subtractInPlace = function (otherVector) {
  3823. this.x -= otherVector.x;
  3824. this.y -= otherVector.y;
  3825. this.z -= otherVector.z;
  3826. this.w -= otherVector.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3831. */
  3832. Vector4.prototype.subtract = function (otherVector) {
  3833. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3834. };
  3835. /**
  3836. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3837. * Returns the current Vector4.
  3838. */
  3839. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3840. result.x = this.x - otherVector.x;
  3841. result.y = this.y - otherVector.y;
  3842. result.z = this.z - otherVector.z;
  3843. result.w = this.w - otherVector.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3848. */
  3849. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3850. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3851. };
  3852. /**
  3853. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3854. * Returns the current Vector4.
  3855. */
  3856. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3857. result.x = this.x - x;
  3858. result.y = this.y - y;
  3859. result.z = this.z - z;
  3860. result.w = this.w - w;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3865. */
  3866. Vector4.prototype.negate = function () {
  3867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3868. };
  3869. /**
  3870. * Multiplies the current Vector4 coordinates by scale (float).
  3871. * Returns the updated Vector4.
  3872. */
  3873. Vector4.prototype.scaleInPlace = function (scale) {
  3874. this.x *= scale;
  3875. this.y *= scale;
  3876. this.z *= scale;
  3877. this.w *= scale;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3882. */
  3883. Vector4.prototype.scale = function (scale) {
  3884. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3885. };
  3886. /**
  3887. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3888. * Returns the current Vector4.
  3889. */
  3890. Vector4.prototype.scaleToRef = function (scale, result) {
  3891. result.x = this.x * scale;
  3892. result.y = this.y * scale;
  3893. result.z = this.z * scale;
  3894. result.w = this.w * scale;
  3895. return this;
  3896. };
  3897. /**
  3898. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3899. * @param scale defines the scale factor
  3900. * @param result defines the Vector4 object where to store the result
  3901. * @returns the unmodified current Vector4
  3902. */
  3903. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3904. result.x += this.x * scale;
  3905. result.y += this.y * scale;
  3906. result.z += this.z * scale;
  3907. result.w += this.w * scale;
  3908. return this;
  3909. };
  3910. /**
  3911. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3912. */
  3913. Vector4.prototype.equals = function (otherVector) {
  3914. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3915. };
  3916. /**
  3917. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3918. */
  3919. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3920. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3921. return otherVector
  3922. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3923. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3925. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3926. };
  3927. /**
  3928. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3929. */
  3930. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3931. return this.x === x && this.y === y && this.z === z && this.w === w;
  3932. };
  3933. /**
  3934. * Multiplies in place the current Vector4 by the passed one.
  3935. * Returns the updated Vector4.
  3936. */
  3937. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3938. this.x *= otherVector.x;
  3939. this.y *= otherVector.y;
  3940. this.z *= otherVector.z;
  3941. this.w *= otherVector.w;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3946. */
  3947. Vector4.prototype.multiply = function (otherVector) {
  3948. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3949. };
  3950. /**
  3951. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3952. * Returns the current Vector4.
  3953. */
  3954. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3955. result.x = this.x * otherVector.x;
  3956. result.y = this.y * otherVector.y;
  3957. result.z = this.z * otherVector.z;
  3958. result.w = this.w * otherVector.w;
  3959. return this;
  3960. };
  3961. /**
  3962. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3963. */
  3964. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3965. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3969. */
  3970. Vector4.prototype.divide = function (otherVector) {
  3971. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3972. };
  3973. /**
  3974. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3975. * Returns the current Vector4.
  3976. */
  3977. Vector4.prototype.divideToRef = function (otherVector, result) {
  3978. result.x = this.x / otherVector.x;
  3979. result.y = this.y / otherVector.y;
  3980. result.z = this.z / otherVector.z;
  3981. result.w = this.w / otherVector.w;
  3982. return this;
  3983. };
  3984. /**
  3985. * Divides the current Vector3 coordinates by the passed ones.
  3986. * @returns the updated Vector3.
  3987. */
  3988. Vector4.prototype.divideInPlace = function (otherVector) {
  3989. return this.divideToRef(otherVector, this);
  3990. };
  3991. /**
  3992. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3993. * @param other defines the second operand
  3994. * @returns the current updated Vector4
  3995. */
  3996. Vector4.prototype.minimizeInPlace = function (other) {
  3997. if (other.x < this.x)
  3998. this.x = other.x;
  3999. if (other.y < this.y)
  4000. this.y = other.y;
  4001. if (other.z < this.z)
  4002. this.z = other.z;
  4003. if (other.w < this.w)
  4004. this.w = other.w;
  4005. return this;
  4006. };
  4007. /**
  4008. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4009. * @param other defines the second operand
  4010. * @returns the current updated Vector4
  4011. */
  4012. Vector4.prototype.maximizeInPlace = function (other) {
  4013. if (other.x > this.x)
  4014. this.x = other.x;
  4015. if (other.y > this.y)
  4016. this.y = other.y;
  4017. if (other.z > this.z)
  4018. this.z = other.z;
  4019. if (other.w > this.w)
  4020. this.w = other.w;
  4021. return this;
  4022. };
  4023. // Properties
  4024. /**
  4025. * Returns the Vector4 length (float).
  4026. */
  4027. Vector4.prototype.length = function () {
  4028. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4029. };
  4030. /**
  4031. * Returns the Vector4 squared length (float).
  4032. */
  4033. Vector4.prototype.lengthSquared = function () {
  4034. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4035. };
  4036. // Methods
  4037. /**
  4038. * Normalizes in place the Vector4.
  4039. * Returns the updated Vector4.
  4040. */
  4041. Vector4.prototype.normalize = function () {
  4042. var len = this.length();
  4043. if (len === 0)
  4044. return this;
  4045. var num = 1.0 / len;
  4046. this.x *= num;
  4047. this.y *= num;
  4048. this.z *= num;
  4049. this.w *= num;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4054. */
  4055. Vector4.prototype.toVector3 = function () {
  4056. return new Vector3(this.x, this.y, this.z);
  4057. };
  4058. /**
  4059. * Returns a new Vector4 copied from the current one.
  4060. */
  4061. Vector4.prototype.clone = function () {
  4062. return new Vector4(this.x, this.y, this.z, this.w);
  4063. };
  4064. /**
  4065. * Updates the current Vector4 with the passed one coordinates.
  4066. * Returns the updated Vector4.
  4067. */
  4068. Vector4.prototype.copyFrom = function (source) {
  4069. this.x = source.x;
  4070. this.y = source.y;
  4071. this.z = source.z;
  4072. this.w = source.w;
  4073. return this;
  4074. };
  4075. /**
  4076. * Updates the current Vector4 coordinates with the passed floats.
  4077. * Returns the updated Vector4.
  4078. */
  4079. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4080. this.x = x;
  4081. this.y = y;
  4082. this.z = z;
  4083. this.w = w;
  4084. return this;
  4085. };
  4086. /**
  4087. * Updates the current Vector4 coordinates with the passed floats.
  4088. * Returns the updated Vector4.
  4089. */
  4090. Vector4.prototype.set = function (x, y, z, w) {
  4091. return this.copyFromFloats(x, y, z, w);
  4092. };
  4093. // Statics
  4094. /**
  4095. * Returns a new Vector4 set from the starting index of the passed array.
  4096. */
  4097. Vector4.FromArray = function (array, offset) {
  4098. if (!offset) {
  4099. offset = 0;
  4100. }
  4101. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4102. };
  4103. /**
  4104. * Updates the passed vector "result" from the starting index of the passed array.
  4105. */
  4106. Vector4.FromArrayToRef = function (array, offset, result) {
  4107. result.x = array[offset];
  4108. result.y = array[offset + 1];
  4109. result.z = array[offset + 2];
  4110. result.w = array[offset + 3];
  4111. };
  4112. /**
  4113. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4114. */
  4115. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4116. Vector4.FromArrayToRef(array, offset, result);
  4117. };
  4118. /**
  4119. * Updates the passed vector "result" coordinates from the passed floats.
  4120. */
  4121. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4122. result.x = x;
  4123. result.y = y;
  4124. result.z = z;
  4125. result.w = w;
  4126. };
  4127. /**
  4128. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4129. */
  4130. Vector4.Zero = function () {
  4131. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4135. */
  4136. Vector4.One = function () {
  4137. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4138. };
  4139. /**
  4140. * Returns a new normalized Vector4 from the passed one.
  4141. */
  4142. Vector4.Normalize = function (vector) {
  4143. var result = Vector4.Zero();
  4144. Vector4.NormalizeToRef(vector, result);
  4145. return result;
  4146. };
  4147. /**
  4148. * Updates the passed vector "result" from the normalization of the passed one.
  4149. */
  4150. Vector4.NormalizeToRef = function (vector, result) {
  4151. result.copyFrom(vector);
  4152. result.normalize();
  4153. };
  4154. Vector4.Minimize = function (left, right) {
  4155. var min = left.clone();
  4156. min.minimizeInPlace(right);
  4157. return min;
  4158. };
  4159. Vector4.Maximize = function (left, right) {
  4160. var max = left.clone();
  4161. max.maximizeInPlace(right);
  4162. return max;
  4163. };
  4164. /**
  4165. * Returns the distance (float) between the vectors "value1" and "value2".
  4166. */
  4167. Vector4.Distance = function (value1, value2) {
  4168. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4169. };
  4170. /**
  4171. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4172. */
  4173. Vector4.DistanceSquared = function (value1, value2) {
  4174. var x = value1.x - value2.x;
  4175. var y = value1.y - value2.y;
  4176. var z = value1.z - value2.z;
  4177. var w = value1.w - value2.w;
  4178. return (x * x) + (y * y) + (z * z) + (w * w);
  4179. };
  4180. /**
  4181. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4182. */
  4183. Vector4.Center = function (value1, value2) {
  4184. var center = value1.add(value2);
  4185. center.scaleInPlace(0.5);
  4186. return center;
  4187. };
  4188. /**
  4189. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4190. * This methods computes transformed normalized direction vectors only.
  4191. */
  4192. Vector4.TransformNormal = function (vector, transformation) {
  4193. var result = Vector4.Zero();
  4194. Vector4.TransformNormalToRef(vector, transformation, result);
  4195. return result;
  4196. };
  4197. /**
  4198. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4199. * This methods computes transformed normalized direction vectors only.
  4200. */
  4201. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4202. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4203. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4204. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4205. result.x = x;
  4206. result.y = y;
  4207. result.z = z;
  4208. result.w = vector.w;
  4209. };
  4210. /**
  4211. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4212. * This methods computes transformed normalized direction vectors only.
  4213. */
  4214. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4215. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4216. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4217. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4218. result.w = w;
  4219. };
  4220. return Vector4;
  4221. }());
  4222. BABYLON.Vector4 = Vector4;
  4223. var Size = /** @class */ (function () {
  4224. /**
  4225. * Creates a Size object from the passed width and height (floats).
  4226. */
  4227. function Size(width, height) {
  4228. this.width = width;
  4229. this.height = height;
  4230. }
  4231. // Returns a string with the Size width and height.
  4232. Size.prototype.toString = function () {
  4233. return "{W: " + this.width + ", H: " + this.height + "}";
  4234. };
  4235. /**
  4236. * Returns the string "Size"
  4237. */
  4238. Size.prototype.getClassName = function () {
  4239. return "Size";
  4240. };
  4241. /**
  4242. * Returns the Size hash code.
  4243. */
  4244. Size.prototype.getHashCode = function () {
  4245. var hash = this.width || 0;
  4246. hash = (hash * 397) ^ (this.height || 0);
  4247. return hash;
  4248. };
  4249. /**
  4250. * Updates the current size from the passed one.
  4251. * Returns the updated Size.
  4252. */
  4253. Size.prototype.copyFrom = function (src) {
  4254. this.width = src.width;
  4255. this.height = src.height;
  4256. };
  4257. /**
  4258. * Updates in place the current Size from the passed floats.
  4259. * Returns the updated Size.
  4260. */
  4261. Size.prototype.copyFromFloats = function (width, height) {
  4262. this.width = width;
  4263. this.height = height;
  4264. return this;
  4265. };
  4266. /**
  4267. * Updates in place the current Size from the passed floats.
  4268. * Returns the updated Size.
  4269. */
  4270. Size.prototype.set = function (width, height) {
  4271. return this.copyFromFloats(width, height);
  4272. };
  4273. /**
  4274. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4275. */
  4276. Size.prototype.multiplyByFloats = function (w, h) {
  4277. return new Size(this.width * w, this.height * h);
  4278. };
  4279. /**
  4280. * Returns a new Size copied from the passed one.
  4281. */
  4282. Size.prototype.clone = function () {
  4283. return new Size(this.width, this.height);
  4284. };
  4285. /**
  4286. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4287. */
  4288. Size.prototype.equals = function (other) {
  4289. if (!other) {
  4290. return false;
  4291. }
  4292. return (this.width === other.width) && (this.height === other.height);
  4293. };
  4294. Object.defineProperty(Size.prototype, "surface", {
  4295. /**
  4296. * Returns the surface of the Size : width * height (float).
  4297. */
  4298. get: function () {
  4299. return this.width * this.height;
  4300. },
  4301. enumerable: true,
  4302. configurable: true
  4303. });
  4304. /**
  4305. * Returns a new Size set to (0.0, 0.0)
  4306. */
  4307. Size.Zero = function () {
  4308. return new Size(0.0, 0.0);
  4309. };
  4310. /**
  4311. * Returns a new Size set as the addition result of the current Size and the passed one.
  4312. */
  4313. Size.prototype.add = function (otherSize) {
  4314. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4315. return r;
  4316. };
  4317. /**
  4318. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4319. */
  4320. Size.prototype.subtract = function (otherSize) {
  4321. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4322. return r;
  4323. };
  4324. /**
  4325. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4326. */
  4327. Size.Lerp = function (start, end, amount) {
  4328. var w = start.width + ((end.width - start.width) * amount);
  4329. var h = start.height + ((end.height - start.height) * amount);
  4330. return new Size(w, h);
  4331. };
  4332. return Size;
  4333. }());
  4334. BABYLON.Size = Size;
  4335. var Quaternion = /** @class */ (function () {
  4336. /**
  4337. * Creates a new Quaternion from the passed floats.
  4338. */
  4339. function Quaternion(x, y, z, w) {
  4340. if (x === void 0) { x = 0.0; }
  4341. if (y === void 0) { y = 0.0; }
  4342. if (z === void 0) { z = 0.0; }
  4343. if (w === void 0) { w = 1.0; }
  4344. this.x = x;
  4345. this.y = y;
  4346. this.z = z;
  4347. this.w = w;
  4348. }
  4349. /**
  4350. * Returns a string with the Quaternion coordinates.
  4351. */
  4352. Quaternion.prototype.toString = function () {
  4353. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4354. };
  4355. /**
  4356. * Returns the string "Quaternion".
  4357. */
  4358. Quaternion.prototype.getClassName = function () {
  4359. return "Quaternion";
  4360. };
  4361. /**
  4362. * Returns the Quaternion hash code.
  4363. */
  4364. Quaternion.prototype.getHashCode = function () {
  4365. var hash = this.x || 0;
  4366. hash = (hash * 397) ^ (this.y || 0);
  4367. hash = (hash * 397) ^ (this.z || 0);
  4368. hash = (hash * 397) ^ (this.w || 0);
  4369. return hash;
  4370. };
  4371. /**
  4372. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4373. */
  4374. Quaternion.prototype.asArray = function () {
  4375. return [this.x, this.y, this.z, this.w];
  4376. };
  4377. /**
  4378. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4379. */
  4380. Quaternion.prototype.equals = function (otherQuaternion) {
  4381. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4382. };
  4383. /**
  4384. * Returns a new Quaternion copied from the current one.
  4385. */
  4386. Quaternion.prototype.clone = function () {
  4387. return new Quaternion(this.x, this.y, this.z, this.w);
  4388. };
  4389. /**
  4390. * Updates the current Quaternion from the passed one coordinates.
  4391. * Returns the updated Quaterion.
  4392. */
  4393. Quaternion.prototype.copyFrom = function (other) {
  4394. this.x = other.x;
  4395. this.y = other.y;
  4396. this.z = other.z;
  4397. this.w = other.w;
  4398. return this;
  4399. };
  4400. /**
  4401. * Updates the current Quaternion from the passed float coordinates.
  4402. * Returns the updated Quaterion.
  4403. */
  4404. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4405. this.x = x;
  4406. this.y = y;
  4407. this.z = z;
  4408. this.w = w;
  4409. return this;
  4410. };
  4411. /**
  4412. * Updates the current Quaternion from the passed float coordinates.
  4413. * Returns the updated Quaterion.
  4414. */
  4415. Quaternion.prototype.set = function (x, y, z, w) {
  4416. return this.copyFromFloats(x, y, z, w);
  4417. };
  4418. /**
  4419. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4420. */
  4421. Quaternion.prototype.add = function (other) {
  4422. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4423. };
  4424. /**
  4425. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4426. */
  4427. Quaternion.prototype.subtract = function (other) {
  4428. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4432. */
  4433. Quaternion.prototype.scale = function (value) {
  4434. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4435. };
  4436. /**
  4437. * Scale the current Quaternion values by a factor to a given Quaternion
  4438. * @param scale defines the scale factor
  4439. * @param result defines the Quaternion object where to store the result
  4440. * @returns the unmodified current Quaternion
  4441. */
  4442. Quaternion.prototype.scaleToRef = function (scale, result) {
  4443. result.x = this.x * scale;
  4444. result.y = this.y * scale;
  4445. result.z = this.z * scale;
  4446. result.w = this.w * scale;
  4447. return this;
  4448. };
  4449. /**
  4450. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4451. * @param scale defines the scale factor
  4452. * @param result defines the Quaternion object where to store the result
  4453. * @returns the unmodified current Quaternion
  4454. */
  4455. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4456. result.x += this.x * scale;
  4457. result.y += this.y * scale;
  4458. result.z += this.z * scale;
  4459. result.w += this.w * scale;
  4460. return this;
  4461. };
  4462. /**
  4463. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4464. */
  4465. Quaternion.prototype.multiply = function (q1) {
  4466. var result = new Quaternion(0, 0, 0, 1.0);
  4467. this.multiplyToRef(q1, result);
  4468. return result;
  4469. };
  4470. /**
  4471. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4472. * Returns the current Quaternion.
  4473. */
  4474. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4475. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4476. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4477. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4478. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4479. result.copyFromFloats(x, y, z, w);
  4480. return this;
  4481. };
  4482. /**
  4483. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4484. * Returns the updated Quaternion.
  4485. */
  4486. Quaternion.prototype.multiplyInPlace = function (q1) {
  4487. this.multiplyToRef(q1, this);
  4488. return this;
  4489. };
  4490. /**
  4491. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4492. * Returns the current Quaternion.
  4493. */
  4494. Quaternion.prototype.conjugateToRef = function (ref) {
  4495. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4496. return this;
  4497. };
  4498. /**
  4499. * Conjugates in place the current Quaternion.
  4500. * Returns the updated Quaternion.
  4501. */
  4502. Quaternion.prototype.conjugateInPlace = function () {
  4503. this.x *= -1;
  4504. this.y *= -1;
  4505. this.z *= -1;
  4506. return this;
  4507. };
  4508. /**
  4509. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4510. */
  4511. Quaternion.prototype.conjugate = function () {
  4512. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4513. return result;
  4514. };
  4515. /**
  4516. * Returns the Quaternion length (float).
  4517. */
  4518. Quaternion.prototype.length = function () {
  4519. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4520. };
  4521. /**
  4522. * Normalize in place the current Quaternion.
  4523. * Returns the updated Quaternion.
  4524. */
  4525. Quaternion.prototype.normalize = function () {
  4526. var length = 1.0 / this.length();
  4527. this.x *= length;
  4528. this.y *= length;
  4529. this.z *= length;
  4530. this.w *= length;
  4531. return this;
  4532. };
  4533. /**
  4534. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4535. * @param order is a reserved parameter and is ignore for now
  4536. * @returns the new Vector3
  4537. */
  4538. Quaternion.prototype.toEulerAngles = function (order) {
  4539. if (order === void 0) { order = "YZX"; }
  4540. var result = Vector3.Zero();
  4541. this.toEulerAnglesToRef(result, order);
  4542. return result;
  4543. };
  4544. /**
  4545. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4546. * @param result defines the vector which will be filled with the Euler angles
  4547. * @param order is a reserved parameter and is ignore for now
  4548. * @returns the current Quaternion
  4549. */
  4550. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4551. if (order === void 0) { order = "YZX"; }
  4552. var qz = this.z;
  4553. var qx = this.x;
  4554. var qy = this.y;
  4555. var qw = this.w;
  4556. var sqw = qw * qw;
  4557. var sqz = qz * qz;
  4558. var sqx = qx * qx;
  4559. var sqy = qy * qy;
  4560. var zAxisY = qy * qz - qx * qw;
  4561. var limit = .4999999;
  4562. if (zAxisY < -limit) {
  4563. result.y = 2 * Math.atan2(qy, qw);
  4564. result.x = Math.PI / 2;
  4565. result.z = 0;
  4566. }
  4567. else if (zAxisY > limit) {
  4568. result.y = 2 * Math.atan2(qy, qw);
  4569. result.x = -Math.PI / 2;
  4570. result.z = 0;
  4571. }
  4572. else {
  4573. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4574. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4575. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4576. }
  4577. return this;
  4578. };
  4579. /**
  4580. * Updates the passed rotation matrix with the current Quaternion values.
  4581. * Returns the current Quaternion.
  4582. */
  4583. Quaternion.prototype.toRotationMatrix = function (result) {
  4584. var xx = this.x * this.x;
  4585. var yy = this.y * this.y;
  4586. var zz = this.z * this.z;
  4587. var xy = this.x * this.y;
  4588. var zw = this.z * this.w;
  4589. var zx = this.z * this.x;
  4590. var yw = this.y * this.w;
  4591. var yz = this.y * this.z;
  4592. var xw = this.x * this.w;
  4593. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4594. result.m[1] = 2.0 * (xy + zw);
  4595. result.m[2] = 2.0 * (zx - yw);
  4596. result.m[3] = 0;
  4597. result.m[4] = 2.0 * (xy - zw);
  4598. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4599. result.m[6] = 2.0 * (yz + xw);
  4600. result.m[7] = 0;
  4601. result.m[8] = 2.0 * (zx + yw);
  4602. result.m[9] = 2.0 * (yz - xw);
  4603. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4604. result.m[11] = 0;
  4605. result.m[12] = 0;
  4606. result.m[13] = 0;
  4607. result.m[14] = 0;
  4608. result.m[15] = 1.0;
  4609. result._markAsUpdated();
  4610. return this;
  4611. };
  4612. /**
  4613. * Updates the current Quaternion from the passed rotation matrix values.
  4614. * Returns the updated Quaternion.
  4615. */
  4616. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4617. Quaternion.FromRotationMatrixToRef(matrix, this);
  4618. return this;
  4619. };
  4620. // Statics
  4621. /**
  4622. * Returns a new Quaternion set from the passed rotation matrix values.
  4623. */
  4624. Quaternion.FromRotationMatrix = function (matrix) {
  4625. var result = new Quaternion();
  4626. Quaternion.FromRotationMatrixToRef(matrix, result);
  4627. return result;
  4628. };
  4629. /**
  4630. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4631. */
  4632. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4633. var data = matrix.m;
  4634. var m11 = data[0], m12 = data[4], m13 = data[8];
  4635. var m21 = data[1], m22 = data[5], m23 = data[9];
  4636. var m31 = data[2], m32 = data[6], m33 = data[10];
  4637. var trace = m11 + m22 + m33;
  4638. var s;
  4639. if (trace > 0) {
  4640. s = 0.5 / Math.sqrt(trace + 1.0);
  4641. result.w = 0.25 / s;
  4642. result.x = (m32 - m23) * s;
  4643. result.y = (m13 - m31) * s;
  4644. result.z = (m21 - m12) * s;
  4645. }
  4646. else if (m11 > m22 && m11 > m33) {
  4647. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4648. result.w = (m32 - m23) / s;
  4649. result.x = 0.25 * s;
  4650. result.y = (m12 + m21) / s;
  4651. result.z = (m13 + m31) / s;
  4652. }
  4653. else if (m22 > m33) {
  4654. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4655. result.w = (m13 - m31) / s;
  4656. result.x = (m12 + m21) / s;
  4657. result.y = 0.25 * s;
  4658. result.z = (m23 + m32) / s;
  4659. }
  4660. else {
  4661. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4662. result.w = (m21 - m12) / s;
  4663. result.x = (m13 + m31) / s;
  4664. result.y = (m23 + m32) / s;
  4665. result.z = 0.25 * s;
  4666. }
  4667. };
  4668. /**
  4669. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4670. */
  4671. Quaternion.Zero = function () {
  4672. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4673. };
  4674. /**
  4675. * Returns a new Quaternion as the inverted current Quaternion.
  4676. */
  4677. Quaternion.Inverse = function (q) {
  4678. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4679. };
  4680. /**
  4681. * Returns the identity Quaternion.
  4682. */
  4683. Quaternion.Identity = function () {
  4684. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4685. };
  4686. Quaternion.IsIdentity = function (quaternion) {
  4687. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4688. };
  4689. /**
  4690. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4691. */
  4692. Quaternion.RotationAxis = function (axis, angle) {
  4693. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4694. };
  4695. /**
  4696. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4697. */
  4698. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4699. var sin = Math.sin(angle / 2);
  4700. axis.normalize();
  4701. result.w = Math.cos(angle / 2);
  4702. result.x = axis.x * sin;
  4703. result.y = axis.y * sin;
  4704. result.z = axis.z * sin;
  4705. return result;
  4706. };
  4707. /**
  4708. * Retuns a new Quaternion set from the starting index of the passed array.
  4709. */
  4710. Quaternion.FromArray = function (array, offset) {
  4711. if (!offset) {
  4712. offset = 0;
  4713. }
  4714. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4715. };
  4716. /**
  4717. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4718. */
  4719. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4720. var q = new Quaternion();
  4721. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4722. return q;
  4723. };
  4724. /**
  4725. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4726. */
  4727. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4728. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4729. var halfRoll = roll * 0.5;
  4730. var halfPitch = pitch * 0.5;
  4731. var halfYaw = yaw * 0.5;
  4732. var sinRoll = Math.sin(halfRoll);
  4733. var cosRoll = Math.cos(halfRoll);
  4734. var sinPitch = Math.sin(halfPitch);
  4735. var cosPitch = Math.cos(halfPitch);
  4736. var sinYaw = Math.sin(halfYaw);
  4737. var cosYaw = Math.cos(halfYaw);
  4738. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4739. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4740. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4741. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4742. };
  4743. /**
  4744. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4745. */
  4746. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4747. var result = new Quaternion();
  4748. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4749. return result;
  4750. };
  4751. /**
  4752. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4753. */
  4754. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4755. // Produces a quaternion from Euler angles in the z-x-z orientation
  4756. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4757. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4758. var halfBeta = beta * 0.5;
  4759. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4760. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4761. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4762. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4763. };
  4764. /**
  4765. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4766. * cf to Vector3.RotationFromAxis() documentation.
  4767. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4768. */
  4769. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4770. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4771. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4772. return quat;
  4773. };
  4774. /**
  4775. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4776. * cf to Vector3.RotationFromAxis() documentation.
  4777. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4778. */
  4779. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4780. var rotMat = MathTmp.Matrix[0];
  4781. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4782. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4783. };
  4784. Quaternion.Slerp = function (left, right, amount) {
  4785. var result = Quaternion.Identity();
  4786. Quaternion.SlerpToRef(left, right, amount, result);
  4787. return result;
  4788. };
  4789. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4790. var num2;
  4791. var num3;
  4792. var num = amount;
  4793. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4794. var flag = false;
  4795. if (num4 < 0) {
  4796. flag = true;
  4797. num4 = -num4;
  4798. }
  4799. if (num4 > 0.999999) {
  4800. num3 = 1 - num;
  4801. num2 = flag ? -num : num;
  4802. }
  4803. else {
  4804. var num5 = Math.acos(num4);
  4805. var num6 = (1.0 / Math.sin(num5));
  4806. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4807. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4808. }
  4809. result.x = (num3 * left.x) + (num2 * right.x);
  4810. result.y = (num3 * left.y) + (num2 * right.y);
  4811. result.z = (num3 * left.z) + (num2 * right.z);
  4812. result.w = (num3 * left.w) + (num2 * right.w);
  4813. };
  4814. /**
  4815. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4816. */
  4817. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4818. var squared = amount * amount;
  4819. var cubed = amount * squared;
  4820. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4821. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4822. var part3 = (cubed - (2.0 * squared)) + amount;
  4823. var part4 = cubed - squared;
  4824. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4825. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4826. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4827. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4828. return new Quaternion(x, y, z, w);
  4829. };
  4830. return Quaternion;
  4831. }());
  4832. BABYLON.Quaternion = Quaternion;
  4833. var Matrix = /** @class */ (function () {
  4834. function Matrix() {
  4835. this._isIdentity = false;
  4836. this._isIdentityDirty = true;
  4837. this.m = new Float32Array(16);
  4838. this._markAsUpdated();
  4839. }
  4840. Matrix.prototype._markAsUpdated = function () {
  4841. this.updateFlag = Matrix._updateFlagSeed++;
  4842. this._isIdentityDirty = true;
  4843. };
  4844. // Properties
  4845. /**
  4846. * Boolean : True is the matrix is the identity matrix
  4847. */
  4848. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4849. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4850. if (this._isIdentityDirty) {
  4851. this._isIdentityDirty = false;
  4852. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4853. this._isIdentity = false;
  4854. }
  4855. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4856. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4857. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4858. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4859. this._isIdentity = false;
  4860. }
  4861. else {
  4862. this._isIdentity = true;
  4863. }
  4864. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4865. this._isIdentity = false;
  4866. }
  4867. }
  4868. return this._isIdentity;
  4869. };
  4870. /**
  4871. * Returns the matrix determinant (float).
  4872. */
  4873. Matrix.prototype.determinant = function () {
  4874. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4875. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4876. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4877. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4878. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4879. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4880. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4881. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4882. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4883. };
  4884. // Methods
  4885. /**
  4886. * Returns the matrix underlying array.
  4887. */
  4888. Matrix.prototype.toArray = function () {
  4889. return this.m;
  4890. };
  4891. /**
  4892. * Returns the matrix underlying array.
  4893. */
  4894. Matrix.prototype.asArray = function () {
  4895. return this.toArray();
  4896. };
  4897. /**
  4898. * Inverts in place the Matrix.
  4899. * Returns the Matrix inverted.
  4900. */
  4901. Matrix.prototype.invert = function () {
  4902. this.invertToRef(this);
  4903. return this;
  4904. };
  4905. /**
  4906. * Sets all the matrix elements to zero.
  4907. * Returns the Matrix.
  4908. */
  4909. Matrix.prototype.reset = function () {
  4910. for (var index = 0; index < 16; index++) {
  4911. this.m[index] = 0.0;
  4912. }
  4913. this._markAsUpdated();
  4914. return this;
  4915. };
  4916. /**
  4917. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4918. */
  4919. Matrix.prototype.add = function (other) {
  4920. var result = new Matrix();
  4921. this.addToRef(other, result);
  4922. return result;
  4923. };
  4924. /**
  4925. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4926. * Returns the Matrix.
  4927. */
  4928. Matrix.prototype.addToRef = function (other, result) {
  4929. for (var index = 0; index < 16; index++) {
  4930. result.m[index] = this.m[index] + other.m[index];
  4931. }
  4932. result._markAsUpdated();
  4933. return this;
  4934. };
  4935. /**
  4936. * Adds in place the passed matrix to the current Matrix.
  4937. * Returns the updated Matrix.
  4938. */
  4939. Matrix.prototype.addToSelf = function (other) {
  4940. for (var index = 0; index < 16; index++) {
  4941. this.m[index] += other.m[index];
  4942. }
  4943. this._markAsUpdated();
  4944. return this;
  4945. };
  4946. /**
  4947. * Sets the passed matrix with the current inverted Matrix.
  4948. * Returns the unmodified current Matrix.
  4949. */
  4950. Matrix.prototype.invertToRef = function (other) {
  4951. var l1 = this.m[0];
  4952. var l2 = this.m[1];
  4953. var l3 = this.m[2];
  4954. var l4 = this.m[3];
  4955. var l5 = this.m[4];
  4956. var l6 = this.m[5];
  4957. var l7 = this.m[6];
  4958. var l8 = this.m[7];
  4959. var l9 = this.m[8];
  4960. var l10 = this.m[9];
  4961. var l11 = this.m[10];
  4962. var l12 = this.m[11];
  4963. var l13 = this.m[12];
  4964. var l14 = this.m[13];
  4965. var l15 = this.m[14];
  4966. var l16 = this.m[15];
  4967. var l17 = (l11 * l16) - (l12 * l15);
  4968. var l18 = (l10 * l16) - (l12 * l14);
  4969. var l19 = (l10 * l15) - (l11 * l14);
  4970. var l20 = (l9 * l16) - (l12 * l13);
  4971. var l21 = (l9 * l15) - (l11 * l13);
  4972. var l22 = (l9 * l14) - (l10 * l13);
  4973. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4974. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4975. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4976. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4977. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4978. var l28 = (l7 * l16) - (l8 * l15);
  4979. var l29 = (l6 * l16) - (l8 * l14);
  4980. var l30 = (l6 * l15) - (l7 * l14);
  4981. var l31 = (l5 * l16) - (l8 * l13);
  4982. var l32 = (l5 * l15) - (l7 * l13);
  4983. var l33 = (l5 * l14) - (l6 * l13);
  4984. var l34 = (l7 * l12) - (l8 * l11);
  4985. var l35 = (l6 * l12) - (l8 * l10);
  4986. var l36 = (l6 * l11) - (l7 * l10);
  4987. var l37 = (l5 * l12) - (l8 * l9);
  4988. var l38 = (l5 * l11) - (l7 * l9);
  4989. var l39 = (l5 * l10) - (l6 * l9);
  4990. other.m[0] = l23 * l27;
  4991. other.m[4] = l24 * l27;
  4992. other.m[8] = l25 * l27;
  4993. other.m[12] = l26 * l27;
  4994. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4995. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4996. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4997. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4998. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4999. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5000. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5001. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5002. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5003. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5004. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5005. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5006. other._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5011. * Returns the updated Matrix.
  5012. */
  5013. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5014. this.m[12] = x;
  5015. this.m[13] = y;
  5016. this.m[14] = z;
  5017. this._markAsUpdated();
  5018. return this;
  5019. };
  5020. /**
  5021. * Inserts the translation vector in the current Matrix.
  5022. * Returns the updated Matrix.
  5023. */
  5024. Matrix.prototype.setTranslation = function (vector3) {
  5025. this.m[12] = vector3.x;
  5026. this.m[13] = vector3.y;
  5027. this.m[14] = vector3.z;
  5028. this._markAsUpdated();
  5029. return this;
  5030. };
  5031. /**
  5032. * Returns a new Vector3 as the extracted translation from the Matrix.
  5033. */
  5034. Matrix.prototype.getTranslation = function () {
  5035. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5036. };
  5037. /**
  5038. * Fill a Vector3 with the extracted translation from the Matrix.
  5039. */
  5040. Matrix.prototype.getTranslationToRef = function (result) {
  5041. result.x = this.m[12];
  5042. result.y = this.m[13];
  5043. result.z = this.m[14];
  5044. return this;
  5045. };
  5046. /**
  5047. * Remove rotation and scaling part from the Matrix.
  5048. * Returns the updated Matrix.
  5049. */
  5050. Matrix.prototype.removeRotationAndScaling = function () {
  5051. this.setRowFromFloats(0, 1, 0, 0, 0);
  5052. this.setRowFromFloats(1, 0, 1, 0, 0);
  5053. this.setRowFromFloats(2, 0, 0, 1, 0);
  5054. return this;
  5055. };
  5056. /**
  5057. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5058. */
  5059. Matrix.prototype.multiply = function (other) {
  5060. var result = new Matrix();
  5061. this.multiplyToRef(other, result);
  5062. return result;
  5063. };
  5064. /**
  5065. * Updates the current Matrix from the passed one values.
  5066. * Returns the updated Matrix.
  5067. */
  5068. Matrix.prototype.copyFrom = function (other) {
  5069. for (var index = 0; index < 16; index++) {
  5070. this.m[index] = other.m[index];
  5071. }
  5072. this._markAsUpdated();
  5073. return this;
  5074. };
  5075. /**
  5076. * Populates the passed array from the starting index with the Matrix values.
  5077. * Returns the Matrix.
  5078. */
  5079. Matrix.prototype.copyToArray = function (array, offset) {
  5080. if (offset === void 0) { offset = 0; }
  5081. for (var index = 0; index < 16; index++) {
  5082. array[offset + index] = this.m[index];
  5083. }
  5084. return this;
  5085. };
  5086. /**
  5087. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5088. */
  5089. Matrix.prototype.multiplyToRef = function (other, result) {
  5090. this.multiplyToArray(other, result.m, 0);
  5091. result._markAsUpdated();
  5092. return this;
  5093. };
  5094. /**
  5095. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5096. */
  5097. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5098. var tm0 = this.m[0];
  5099. var tm1 = this.m[1];
  5100. var tm2 = this.m[2];
  5101. var tm3 = this.m[3];
  5102. var tm4 = this.m[4];
  5103. var tm5 = this.m[5];
  5104. var tm6 = this.m[6];
  5105. var tm7 = this.m[7];
  5106. var tm8 = this.m[8];
  5107. var tm9 = this.m[9];
  5108. var tm10 = this.m[10];
  5109. var tm11 = this.m[11];
  5110. var tm12 = this.m[12];
  5111. var tm13 = this.m[13];
  5112. var tm14 = this.m[14];
  5113. var tm15 = this.m[15];
  5114. var om0 = other.m[0];
  5115. var om1 = other.m[1];
  5116. var om2 = other.m[2];
  5117. var om3 = other.m[3];
  5118. var om4 = other.m[4];
  5119. var om5 = other.m[5];
  5120. var om6 = other.m[6];
  5121. var om7 = other.m[7];
  5122. var om8 = other.m[8];
  5123. var om9 = other.m[9];
  5124. var om10 = other.m[10];
  5125. var om11 = other.m[11];
  5126. var om12 = other.m[12];
  5127. var om13 = other.m[13];
  5128. var om14 = other.m[14];
  5129. var om15 = other.m[15];
  5130. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5131. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5132. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5133. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5134. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5135. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5136. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5137. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5138. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5139. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5140. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5141. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5142. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5143. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5144. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5145. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5146. return this;
  5147. };
  5148. /**
  5149. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5150. */
  5151. Matrix.prototype.equals = function (value) {
  5152. return value &&
  5153. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5154. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5155. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5156. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5157. };
  5158. /**
  5159. * Returns a new Matrix from the current Matrix.
  5160. */
  5161. Matrix.prototype.clone = function () {
  5162. 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]);
  5163. };
  5164. /**
  5165. * Returns the string "Matrix"
  5166. */
  5167. Matrix.prototype.getClassName = function () {
  5168. return "Matrix";
  5169. };
  5170. /**
  5171. * Returns the Matrix hash code.
  5172. */
  5173. Matrix.prototype.getHashCode = function () {
  5174. var hash = this.m[0] || 0;
  5175. for (var i = 1; i < 16; i++) {
  5176. hash = (hash * 397) ^ (this.m[i] || 0);
  5177. }
  5178. return hash;
  5179. };
  5180. /**
  5181. * Decomposes the current Matrix into :
  5182. * - a scale vector3 passed as a reference to update,
  5183. * - a rotation quaternion passed as a reference to update,
  5184. * - a translation vector3 passed as a reference to update.
  5185. * Returns the true if operation was successful.
  5186. */
  5187. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5188. translation.x = this.m[12];
  5189. translation.y = this.m[13];
  5190. translation.z = this.m[14];
  5191. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5192. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5193. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5194. if (this.determinant() <= 0) {
  5195. scale.y *= -1;
  5196. }
  5197. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5198. rotation.x = 0;
  5199. rotation.y = 0;
  5200. rotation.z = 0;
  5201. rotation.w = 1;
  5202. return false;
  5203. }
  5204. 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]);
  5205. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5206. return true;
  5207. };
  5208. /**
  5209. * Returns the index-th row of the current matrix as a new Vector4.
  5210. */
  5211. Matrix.prototype.getRow = function (index) {
  5212. if (index < 0 || index > 3) {
  5213. return null;
  5214. }
  5215. var i = index * 4;
  5216. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5217. };
  5218. /**
  5219. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5220. * Returns the updated Matrix.
  5221. */
  5222. Matrix.prototype.setRow = function (index, row) {
  5223. if (index < 0 || index > 3) {
  5224. return this;
  5225. }
  5226. var i = index * 4;
  5227. this.m[i + 0] = row.x;
  5228. this.m[i + 1] = row.y;
  5229. this.m[i + 2] = row.z;
  5230. this.m[i + 3] = row.w;
  5231. this._markAsUpdated();
  5232. return this;
  5233. };
  5234. /**
  5235. * Compute the transpose of the matrix.
  5236. * Returns a new Matrix.
  5237. */
  5238. Matrix.prototype.transpose = function () {
  5239. return Matrix.Transpose(this);
  5240. };
  5241. /**
  5242. * Compute the transpose of the matrix.
  5243. * Returns the current matrix.
  5244. */
  5245. Matrix.prototype.transposeToRef = function (result) {
  5246. Matrix.TransposeToRef(this, result);
  5247. return this;
  5248. };
  5249. /**
  5250. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5251. * Returns the updated Matrix.
  5252. */
  5253. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5254. if (index < 0 || index > 3) {
  5255. return this;
  5256. }
  5257. var i = index * 4;
  5258. this.m[i + 0] = x;
  5259. this.m[i + 1] = y;
  5260. this.m[i + 2] = z;
  5261. this.m[i + 3] = w;
  5262. this._markAsUpdated();
  5263. return this;
  5264. };
  5265. /**
  5266. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5267. * @param scale defines the scale factor
  5268. * @returns a new Matrix
  5269. */
  5270. Matrix.prototype.scale = function (scale) {
  5271. var result = new Matrix();
  5272. this.scaleToRef(scale, result);
  5273. return result;
  5274. };
  5275. /**
  5276. * Scale the current Matrix values by a factor to a given result Matrix
  5277. * @param scale defines the scale factor
  5278. * @param result defines the Matrix to store the result
  5279. * @returns the current Matrix
  5280. */
  5281. Matrix.prototype.scaleToRef = function (scale, result) {
  5282. for (var index = 0; index < 16; index++) {
  5283. result.m[index] = this.m[index] * scale;
  5284. }
  5285. result._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5290. * @param scale defines the scale factor
  5291. * @param result defines the Matrix to store the result
  5292. * @returns the current Matrix
  5293. */
  5294. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5295. for (var index = 0; index < 16; index++) {
  5296. result.m[index] += this.m[index] * scale;
  5297. }
  5298. result._markAsUpdated();
  5299. return this;
  5300. };
  5301. /**
  5302. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5303. * @param ref matrix to store the result
  5304. */
  5305. Matrix.prototype.toNormalMatrix = function (ref) {
  5306. this.invertToRef(ref);
  5307. ref.transpose();
  5308. var m = ref.m;
  5309. 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);
  5310. };
  5311. /**
  5312. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5313. */
  5314. Matrix.prototype.getRotationMatrix = function () {
  5315. var result = Matrix.Identity();
  5316. this.getRotationMatrixToRef(result);
  5317. return result;
  5318. };
  5319. /**
  5320. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5321. * Returns the current Matrix.
  5322. */
  5323. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5324. var m = this.m;
  5325. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5326. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5327. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5328. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5329. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5330. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5331. 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);
  5332. return this;
  5333. };
  5334. // Statics
  5335. /**
  5336. * Returns a new Matrix set from the starting index of the passed array.
  5337. */
  5338. Matrix.FromArray = function (array, offset) {
  5339. var result = new Matrix();
  5340. if (!offset) {
  5341. offset = 0;
  5342. }
  5343. Matrix.FromArrayToRef(array, offset, result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Sets the passed "result" matrix from the starting index of the passed array.
  5348. */
  5349. Matrix.FromArrayToRef = function (array, offset, result) {
  5350. for (var index = 0; index < 16; index++) {
  5351. result.m[index] = array[index + offset];
  5352. }
  5353. result._markAsUpdated();
  5354. };
  5355. /**
  5356. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5357. */
  5358. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5359. for (var index = 0; index < 16; index++) {
  5360. result.m[index] = array[index + offset] * scale;
  5361. }
  5362. result._markAsUpdated();
  5363. };
  5364. /**
  5365. * Sets the passed matrix "result" with the 16 passed floats.
  5366. */
  5367. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5368. result.m[0] = initialM11;
  5369. result.m[1] = initialM12;
  5370. result.m[2] = initialM13;
  5371. result.m[3] = initialM14;
  5372. result.m[4] = initialM21;
  5373. result.m[5] = initialM22;
  5374. result.m[6] = initialM23;
  5375. result.m[7] = initialM24;
  5376. result.m[8] = initialM31;
  5377. result.m[9] = initialM32;
  5378. result.m[10] = initialM33;
  5379. result.m[11] = initialM34;
  5380. result.m[12] = initialM41;
  5381. result.m[13] = initialM42;
  5382. result.m[14] = initialM43;
  5383. result.m[15] = initialM44;
  5384. result._markAsUpdated();
  5385. };
  5386. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5387. /**
  5388. * Static identity matrix to be used as readonly matrix
  5389. * Must not be updated.
  5390. */
  5391. get: function () {
  5392. return Matrix._identityReadOnly;
  5393. },
  5394. enumerable: true,
  5395. configurable: true
  5396. });
  5397. /**
  5398. * Returns a new Matrix set from the 16 passed floats.
  5399. */
  5400. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5401. var result = new Matrix();
  5402. result.m[0] = initialM11;
  5403. result.m[1] = initialM12;
  5404. result.m[2] = initialM13;
  5405. result.m[3] = initialM14;
  5406. result.m[4] = initialM21;
  5407. result.m[5] = initialM22;
  5408. result.m[6] = initialM23;
  5409. result.m[7] = initialM24;
  5410. result.m[8] = initialM31;
  5411. result.m[9] = initialM32;
  5412. result.m[10] = initialM33;
  5413. result.m[11] = initialM34;
  5414. result.m[12] = initialM41;
  5415. result.m[13] = initialM42;
  5416. result.m[14] = initialM43;
  5417. result.m[15] = initialM44;
  5418. return result;
  5419. };
  5420. /**
  5421. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5422. */
  5423. Matrix.Compose = function (scale, rotation, translation) {
  5424. var result = Matrix.Identity();
  5425. Matrix.ComposeToRef(scale, rotation, translation, result);
  5426. return result;
  5427. };
  5428. /**
  5429. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5430. */
  5431. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5432. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5433. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5434. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5435. result.setTranslation(translation);
  5436. };
  5437. /**
  5438. * Returns a new indentity Matrix.
  5439. */
  5440. Matrix.Identity = function () {
  5441. 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);
  5442. };
  5443. /**
  5444. * Sets the passed "result" as an identity matrix.
  5445. */
  5446. Matrix.IdentityToRef = function (result) {
  5447. 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);
  5448. };
  5449. /**
  5450. * Returns a new zero Matrix.
  5451. */
  5452. Matrix.Zero = function () {
  5453. 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);
  5454. };
  5455. /**
  5456. * Returns a new rotation matrix for "angle" radians around the X axis.
  5457. */
  5458. Matrix.RotationX = function (angle) {
  5459. var result = new Matrix();
  5460. Matrix.RotationXToRef(angle, result);
  5461. return result;
  5462. };
  5463. /**
  5464. * Returns a new Matrix as the passed inverted one.
  5465. */
  5466. Matrix.Invert = function (source) {
  5467. var result = new Matrix();
  5468. source.invertToRef(result);
  5469. return result;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5473. */
  5474. Matrix.RotationXToRef = function (angle, result) {
  5475. var s = Math.sin(angle);
  5476. var c = Math.cos(angle);
  5477. result.m[0] = 1.0;
  5478. result.m[15] = 1.0;
  5479. result.m[5] = c;
  5480. result.m[10] = c;
  5481. result.m[9] = -s;
  5482. result.m[6] = s;
  5483. result.m[1] = 0.0;
  5484. result.m[2] = 0.0;
  5485. result.m[3] = 0.0;
  5486. result.m[4] = 0.0;
  5487. result.m[7] = 0.0;
  5488. result.m[8] = 0.0;
  5489. result.m[11] = 0.0;
  5490. result.m[12] = 0.0;
  5491. result.m[13] = 0.0;
  5492. result.m[14] = 0.0;
  5493. result._markAsUpdated();
  5494. };
  5495. /**
  5496. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5497. */
  5498. Matrix.RotationY = function (angle) {
  5499. var result = new Matrix();
  5500. Matrix.RotationYToRef(angle, result);
  5501. return result;
  5502. };
  5503. /**
  5504. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5505. */
  5506. Matrix.RotationYToRef = function (angle, result) {
  5507. var s = Math.sin(angle);
  5508. var c = Math.cos(angle);
  5509. result.m[5] = 1.0;
  5510. result.m[15] = 1.0;
  5511. result.m[0] = c;
  5512. result.m[2] = -s;
  5513. result.m[8] = s;
  5514. result.m[10] = c;
  5515. result.m[1] = 0.0;
  5516. result.m[3] = 0.0;
  5517. result.m[4] = 0.0;
  5518. result.m[6] = 0.0;
  5519. result.m[7] = 0.0;
  5520. result.m[9] = 0.0;
  5521. result.m[11] = 0.0;
  5522. result.m[12] = 0.0;
  5523. result.m[13] = 0.0;
  5524. result.m[14] = 0.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5529. */
  5530. Matrix.RotationZ = function (angle) {
  5531. var result = new Matrix();
  5532. Matrix.RotationZToRef(angle, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5537. */
  5538. Matrix.RotationZToRef = function (angle, result) {
  5539. var s = Math.sin(angle);
  5540. var c = Math.cos(angle);
  5541. result.m[10] = 1.0;
  5542. result.m[15] = 1.0;
  5543. result.m[0] = c;
  5544. result.m[1] = s;
  5545. result.m[4] = -s;
  5546. result.m[5] = c;
  5547. result.m[2] = 0.0;
  5548. result.m[3] = 0.0;
  5549. result.m[6] = 0.0;
  5550. result.m[7] = 0.0;
  5551. result.m[8] = 0.0;
  5552. result.m[9] = 0.0;
  5553. result.m[11] = 0.0;
  5554. result.m[12] = 0.0;
  5555. result.m[13] = 0.0;
  5556. result.m[14] = 0.0;
  5557. result._markAsUpdated();
  5558. };
  5559. /**
  5560. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5561. */
  5562. Matrix.RotationAxis = function (axis, angle) {
  5563. var result = Matrix.Zero();
  5564. Matrix.RotationAxisToRef(axis, angle, result);
  5565. return result;
  5566. };
  5567. /**
  5568. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5569. */
  5570. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5571. var s = Math.sin(-angle);
  5572. var c = Math.cos(-angle);
  5573. var c1 = 1 - c;
  5574. axis.normalize();
  5575. result.m[0] = (axis.x * axis.x) * c1 + c;
  5576. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5577. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5578. result.m[3] = 0.0;
  5579. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5580. result.m[5] = (axis.y * axis.y) * c1 + c;
  5581. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5582. result.m[7] = 0.0;
  5583. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5584. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5585. result.m[10] = (axis.z * axis.z) * c1 + c;
  5586. result.m[11] = 0.0;
  5587. result.m[15] = 1.0;
  5588. result._markAsUpdated();
  5589. };
  5590. /**
  5591. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5592. */
  5593. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5594. var result = new Matrix();
  5595. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5600. */
  5601. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5602. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5603. this._tempQuaternion.toRotationMatrix(result);
  5604. };
  5605. /**
  5606. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5607. */
  5608. Matrix.Scaling = function (x, y, z) {
  5609. var result = Matrix.Zero();
  5610. Matrix.ScalingToRef(x, y, z, result);
  5611. return result;
  5612. };
  5613. /**
  5614. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5615. */
  5616. Matrix.ScalingToRef = function (x, y, z, result) {
  5617. result.m[0] = x;
  5618. result.m[1] = 0.0;
  5619. result.m[2] = 0.0;
  5620. result.m[3] = 0.0;
  5621. result.m[4] = 0.0;
  5622. result.m[5] = y;
  5623. result.m[6] = 0.0;
  5624. result.m[7] = 0.0;
  5625. result.m[8] = 0.0;
  5626. result.m[9] = 0.0;
  5627. result.m[10] = z;
  5628. result.m[11] = 0.0;
  5629. result.m[12] = 0.0;
  5630. result.m[13] = 0.0;
  5631. result.m[14] = 0.0;
  5632. result.m[15] = 1.0;
  5633. result._markAsUpdated();
  5634. };
  5635. /**
  5636. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5637. */
  5638. Matrix.Translation = function (x, y, z) {
  5639. var result = Matrix.Identity();
  5640. Matrix.TranslationToRef(x, y, z, result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5645. */
  5646. Matrix.TranslationToRef = function (x, y, z, result) {
  5647. 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);
  5648. };
  5649. /**
  5650. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5651. * @param startValue defines the start value
  5652. * @param endValue defines the end value
  5653. * @param gradient defines the gradient factor
  5654. * @returns the new matrix
  5655. */
  5656. Matrix.Lerp = function (startValue, endValue, gradient) {
  5657. var result = Matrix.Zero();
  5658. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5659. return result;
  5660. };
  5661. /**
  5662. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5663. * @param startValue defines the start value
  5664. * @param endValue defines the end value
  5665. * @param gradient defines the gradient factor
  5666. * @param result defines the Matrix object where to store data
  5667. */
  5668. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5669. for (var index = 0; index < 16; index++) {
  5670. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5671. }
  5672. result._markAsUpdated();
  5673. };
  5674. /**
  5675. * Returns a new Matrix whose values are computed by :
  5676. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5677. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5678. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5679. */
  5680. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5681. var startScale = new Vector3(0, 0, 0);
  5682. var startRotation = new Quaternion();
  5683. var startTranslation = new Vector3(0, 0, 0);
  5684. startValue.decompose(startScale, startRotation, startTranslation);
  5685. var endScale = new Vector3(0, 0, 0);
  5686. var endRotation = new Quaternion();
  5687. var endTranslation = new Vector3(0, 0, 0);
  5688. endValue.decompose(endScale, endRotation, endTranslation);
  5689. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5690. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5691. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5692. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5693. };
  5694. /**
  5695. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5696. * This methods works for a Left-Handed system.
  5697. */
  5698. Matrix.LookAtLH = function (eye, target, up) {
  5699. var result = Matrix.Zero();
  5700. Matrix.LookAtLHToRef(eye, target, up, result);
  5701. return result;
  5702. };
  5703. /**
  5704. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5705. * This methods works for a Left-Handed system.
  5706. */
  5707. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5708. // Z axis
  5709. target.subtractToRef(eye, this._zAxis);
  5710. this._zAxis.normalize();
  5711. // X axis
  5712. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5713. if (this._xAxis.lengthSquared() === 0) {
  5714. this._xAxis.x = 1.0;
  5715. }
  5716. else {
  5717. this._xAxis.normalize();
  5718. }
  5719. // Y axis
  5720. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5721. this._yAxis.normalize();
  5722. // Eye angles
  5723. var ex = -Vector3.Dot(this._xAxis, eye);
  5724. var ey = -Vector3.Dot(this._yAxis, eye);
  5725. var ez = -Vector3.Dot(this._zAxis, eye);
  5726. 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);
  5727. };
  5728. /**
  5729. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5730. * This methods works for a Right-Handed system.
  5731. */
  5732. Matrix.LookAtRH = function (eye, target, up) {
  5733. var result = Matrix.Zero();
  5734. Matrix.LookAtRHToRef(eye, target, up, result);
  5735. return result;
  5736. };
  5737. /**
  5738. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5739. * This methods works for a Left-Handed system.
  5740. */
  5741. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5742. // Z axis
  5743. eye.subtractToRef(target, this._zAxis);
  5744. this._zAxis.normalize();
  5745. // X axis
  5746. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5747. if (this._xAxis.lengthSquared() === 0) {
  5748. this._xAxis.x = 1.0;
  5749. }
  5750. else {
  5751. this._xAxis.normalize();
  5752. }
  5753. // Y axis
  5754. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5755. this._yAxis.normalize();
  5756. // Eye angles
  5757. var ex = -Vector3.Dot(this._xAxis, eye);
  5758. var ey = -Vector3.Dot(this._yAxis, eye);
  5759. var ez = -Vector3.Dot(this._zAxis, eye);
  5760. 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);
  5761. };
  5762. /**
  5763. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5764. */
  5765. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5766. var matrix = Matrix.Zero();
  5767. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5768. return matrix;
  5769. };
  5770. /**
  5771. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5772. */
  5773. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5774. var n = znear;
  5775. var f = zfar;
  5776. var a = 2.0 / width;
  5777. var b = 2.0 / height;
  5778. var c = 2.0 / (f - n);
  5779. var d = -(f + n) / (f - n);
  5780. 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);
  5781. };
  5782. /**
  5783. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5784. */
  5785. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5786. var matrix = Matrix.Zero();
  5787. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5788. return matrix;
  5789. };
  5790. /**
  5791. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5792. */
  5793. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5794. var n = znear;
  5795. var f = zfar;
  5796. var a = 2.0 / (right - left);
  5797. var b = 2.0 / (top - bottom);
  5798. var c = 2.0 / (f - n);
  5799. var d = -(f + n) / (f - n);
  5800. var i0 = (left + right) / (left - right);
  5801. var i1 = (top + bottom) / (bottom - top);
  5802. 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);
  5803. };
  5804. /**
  5805. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5806. */
  5807. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5808. var matrix = Matrix.Zero();
  5809. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5810. return matrix;
  5811. };
  5812. /**
  5813. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5814. */
  5815. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5816. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5817. result.m[10] *= -1.0;
  5818. };
  5819. /**
  5820. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5821. */
  5822. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5823. var matrix = Matrix.Zero();
  5824. var n = znear;
  5825. var f = zfar;
  5826. var a = 2.0 * n / width;
  5827. var b = 2.0 * n / height;
  5828. var c = (f + n) / (f - n);
  5829. var d = -2.0 * f * n / (f - n);
  5830. 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);
  5831. return matrix;
  5832. };
  5833. /**
  5834. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5835. */
  5836. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5837. var matrix = Matrix.Zero();
  5838. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5839. return matrix;
  5840. };
  5841. /**
  5842. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5843. */
  5844. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5845. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5846. var n = znear;
  5847. var f = zfar;
  5848. var t = 1.0 / (Math.tan(fov * 0.5));
  5849. var a = isVerticalFovFixed ? (t / aspect) : t;
  5850. var b = isVerticalFovFixed ? t : (t * aspect);
  5851. var c = (f + n) / (f - n);
  5852. var d = -2.0 * f * n / (f - n);
  5853. 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);
  5854. };
  5855. /**
  5856. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5857. */
  5858. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5859. var matrix = Matrix.Zero();
  5860. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5861. return matrix;
  5862. };
  5863. /**
  5864. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5865. */
  5866. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5867. //alternatively this could be expressed as:
  5868. // m = PerspectiveFovLHToRef
  5869. // m[10] *= -1.0;
  5870. // m[11] *= -1.0;
  5871. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5872. var n = znear;
  5873. var f = zfar;
  5874. var t = 1.0 / (Math.tan(fov * 0.5));
  5875. var a = isVerticalFovFixed ? (t / aspect) : t;
  5876. var b = isVerticalFovFixed ? t : (t * aspect);
  5877. var c = -(f + n) / (f - n);
  5878. var d = -2 * f * n / (f - n);
  5879. 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);
  5880. };
  5881. /**
  5882. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5883. */
  5884. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5885. if (rightHanded === void 0) { rightHanded = false; }
  5886. var rightHandedFactor = rightHanded ? -1 : 1;
  5887. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5888. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5889. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5890. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5891. var xScale = 2.0 / (leftTan + rightTan);
  5892. var yScale = 2.0 / (upTan + downTan);
  5893. result.m[0] = xScale;
  5894. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5895. result.m[5] = yScale;
  5896. result.m[6] = result.m[7] = 0.0;
  5897. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5898. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5899. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5900. result.m[10] = -zfar / (znear - zfar);
  5901. result.m[11] = 1.0 * rightHandedFactor;
  5902. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5903. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5904. // result.m[14] = (znear * zfar) / (znear - zfar);
  5905. result._markAsUpdated();
  5906. };
  5907. /**
  5908. * Returns the final transformation matrix : world * view * projection * viewport
  5909. */
  5910. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5911. var cw = viewport.width;
  5912. var ch = viewport.height;
  5913. var cx = viewport.x;
  5914. var cy = viewport.y;
  5915. 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);
  5916. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5917. };
  5918. /**
  5919. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5920. */
  5921. Matrix.GetAsMatrix2x2 = function (matrix) {
  5922. return new Float32Array([
  5923. matrix.m[0], matrix.m[1],
  5924. matrix.m[4], matrix.m[5]
  5925. ]);
  5926. };
  5927. /**
  5928. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5929. */
  5930. Matrix.GetAsMatrix3x3 = function (matrix) {
  5931. return new Float32Array([
  5932. matrix.m[0], matrix.m[1], matrix.m[2],
  5933. matrix.m[4], matrix.m[5], matrix.m[6],
  5934. matrix.m[8], matrix.m[9], matrix.m[10]
  5935. ]);
  5936. };
  5937. /**
  5938. * Compute the transpose of the passed Matrix.
  5939. * Returns a new Matrix.
  5940. */
  5941. Matrix.Transpose = function (matrix) {
  5942. var result = new Matrix();
  5943. Matrix.TransposeToRef(matrix, result);
  5944. return result;
  5945. };
  5946. /**
  5947. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5948. */
  5949. Matrix.TransposeToRef = function (matrix, result) {
  5950. result.m[0] = matrix.m[0];
  5951. result.m[1] = matrix.m[4];
  5952. result.m[2] = matrix.m[8];
  5953. result.m[3] = matrix.m[12];
  5954. result.m[4] = matrix.m[1];
  5955. result.m[5] = matrix.m[5];
  5956. result.m[6] = matrix.m[9];
  5957. result.m[7] = matrix.m[13];
  5958. result.m[8] = matrix.m[2];
  5959. result.m[9] = matrix.m[6];
  5960. result.m[10] = matrix.m[10];
  5961. result.m[11] = matrix.m[14];
  5962. result.m[12] = matrix.m[3];
  5963. result.m[13] = matrix.m[7];
  5964. result.m[14] = matrix.m[11];
  5965. result.m[15] = matrix.m[15];
  5966. };
  5967. /**
  5968. * Returns a new Matrix as the reflection matrix across the passed plane.
  5969. */
  5970. Matrix.Reflection = function (plane) {
  5971. var matrix = new Matrix();
  5972. Matrix.ReflectionToRef(plane, matrix);
  5973. return matrix;
  5974. };
  5975. /**
  5976. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5977. */
  5978. Matrix.ReflectionToRef = function (plane, result) {
  5979. plane.normalize();
  5980. var x = plane.normal.x;
  5981. var y = plane.normal.y;
  5982. var z = plane.normal.z;
  5983. var temp = -2 * x;
  5984. var temp2 = -2 * y;
  5985. var temp3 = -2 * z;
  5986. result.m[0] = (temp * x) + 1;
  5987. result.m[1] = temp2 * x;
  5988. result.m[2] = temp3 * x;
  5989. result.m[3] = 0.0;
  5990. result.m[4] = temp * y;
  5991. result.m[5] = (temp2 * y) + 1;
  5992. result.m[6] = temp3 * y;
  5993. result.m[7] = 0.0;
  5994. result.m[8] = temp * z;
  5995. result.m[9] = temp2 * z;
  5996. result.m[10] = (temp3 * z) + 1;
  5997. result.m[11] = 0.0;
  5998. result.m[12] = temp * plane.d;
  5999. result.m[13] = temp2 * plane.d;
  6000. result.m[14] = temp3 * plane.d;
  6001. result.m[15] = 1.0;
  6002. result._markAsUpdated();
  6003. };
  6004. /**
  6005. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6006. */
  6007. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6008. result.m[0] = xaxis.x;
  6009. result.m[1] = xaxis.y;
  6010. result.m[2] = xaxis.z;
  6011. result.m[3] = 0.0;
  6012. result.m[4] = yaxis.x;
  6013. result.m[5] = yaxis.y;
  6014. result.m[6] = yaxis.z;
  6015. result.m[7] = 0.0;
  6016. result.m[8] = zaxis.x;
  6017. result.m[9] = zaxis.y;
  6018. result.m[10] = zaxis.z;
  6019. result.m[11] = 0.0;
  6020. result.m[12] = 0.0;
  6021. result.m[13] = 0.0;
  6022. result.m[14] = 0.0;
  6023. result.m[15] = 1.0;
  6024. result._markAsUpdated();
  6025. };
  6026. /**
  6027. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6028. */
  6029. Matrix.FromQuaternionToRef = function (quat, result) {
  6030. var xx = quat.x * quat.x;
  6031. var yy = quat.y * quat.y;
  6032. var zz = quat.z * quat.z;
  6033. var xy = quat.x * quat.y;
  6034. var zw = quat.z * quat.w;
  6035. var zx = quat.z * quat.x;
  6036. var yw = quat.y * quat.w;
  6037. var yz = quat.y * quat.z;
  6038. var xw = quat.x * quat.w;
  6039. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6040. result.m[1] = 2.0 * (xy + zw);
  6041. result.m[2] = 2.0 * (zx - yw);
  6042. result.m[3] = 0.0;
  6043. result.m[4] = 2.0 * (xy - zw);
  6044. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6045. result.m[6] = 2.0 * (yz + xw);
  6046. result.m[7] = 0.0;
  6047. result.m[8] = 2.0 * (zx + yw);
  6048. result.m[9] = 2.0 * (yz - xw);
  6049. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6050. result.m[11] = 0.0;
  6051. result.m[12] = 0.0;
  6052. result.m[13] = 0.0;
  6053. result.m[14] = 0.0;
  6054. result.m[15] = 1.0;
  6055. result._markAsUpdated();
  6056. };
  6057. Matrix._tempQuaternion = new Quaternion();
  6058. Matrix._xAxis = Vector3.Zero();
  6059. Matrix._yAxis = Vector3.Zero();
  6060. Matrix._zAxis = Vector3.Zero();
  6061. Matrix._updateFlagSeed = 0;
  6062. Matrix._identityReadOnly = Matrix.Identity();
  6063. return Matrix;
  6064. }());
  6065. BABYLON.Matrix = Matrix;
  6066. var Plane = /** @class */ (function () {
  6067. /**
  6068. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6069. */
  6070. function Plane(a, b, c, d) {
  6071. this.normal = new Vector3(a, b, c);
  6072. this.d = d;
  6073. }
  6074. /**
  6075. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6076. */
  6077. Plane.prototype.asArray = function () {
  6078. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6079. };
  6080. // Methods
  6081. /**
  6082. * Returns a new plane copied from the current Plane.
  6083. */
  6084. Plane.prototype.clone = function () {
  6085. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6086. };
  6087. /**
  6088. * Returns the string "Plane".
  6089. */
  6090. Plane.prototype.getClassName = function () {
  6091. return "Plane";
  6092. };
  6093. /**
  6094. * Returns the Plane hash code.
  6095. */
  6096. Plane.prototype.getHashCode = function () {
  6097. var hash = this.normal.getHashCode();
  6098. hash = (hash * 397) ^ (this.d || 0);
  6099. return hash;
  6100. };
  6101. /**
  6102. * Normalize the current Plane in place.
  6103. * Returns the updated Plane.
  6104. */
  6105. Plane.prototype.normalize = function () {
  6106. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6107. var magnitude = 0.0;
  6108. if (norm !== 0) {
  6109. magnitude = 1.0 / norm;
  6110. }
  6111. this.normal.x *= magnitude;
  6112. this.normal.y *= magnitude;
  6113. this.normal.z *= magnitude;
  6114. this.d *= magnitude;
  6115. return this;
  6116. };
  6117. /**
  6118. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6119. */
  6120. Plane.prototype.transform = function (transformation) {
  6121. var transposedMatrix = Matrix.Transpose(transformation);
  6122. var x = this.normal.x;
  6123. var y = this.normal.y;
  6124. var z = this.normal.z;
  6125. var d = this.d;
  6126. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6127. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6128. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6129. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6130. return new Plane(normalX, normalY, normalZ, finalD);
  6131. };
  6132. /**
  6133. * Returns the dot product (float) of the point coordinates and the plane normal.
  6134. */
  6135. Plane.prototype.dotCoordinate = function (point) {
  6136. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6137. };
  6138. /**
  6139. * Updates the current Plane from the plane defined by the three passed points.
  6140. * Returns the updated Plane.
  6141. */
  6142. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6143. var x1 = point2.x - point1.x;
  6144. var y1 = point2.y - point1.y;
  6145. var z1 = point2.z - point1.z;
  6146. var x2 = point3.x - point1.x;
  6147. var y2 = point3.y - point1.y;
  6148. var z2 = point3.z - point1.z;
  6149. var yz = (y1 * z2) - (z1 * y2);
  6150. var xz = (z1 * x2) - (x1 * z2);
  6151. var xy = (x1 * y2) - (y1 * x2);
  6152. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6153. var invPyth;
  6154. if (pyth !== 0) {
  6155. invPyth = 1.0 / pyth;
  6156. }
  6157. else {
  6158. invPyth = 0.0;
  6159. }
  6160. this.normal.x = yz * invPyth;
  6161. this.normal.y = xz * invPyth;
  6162. this.normal.z = xy * invPyth;
  6163. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6164. return this;
  6165. };
  6166. /**
  6167. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6168. */
  6169. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6170. var dot = Vector3.Dot(this.normal, direction);
  6171. return (dot <= epsilon);
  6172. };
  6173. /**
  6174. * Returns the signed distance (float) from the passed point to the Plane.
  6175. */
  6176. Plane.prototype.signedDistanceTo = function (point) {
  6177. return Vector3.Dot(point, this.normal) + this.d;
  6178. };
  6179. // Statics
  6180. /**
  6181. * Returns a new Plane from the passed array.
  6182. */
  6183. Plane.FromArray = function (array) {
  6184. return new Plane(array[0], array[1], array[2], array[3]);
  6185. };
  6186. /**
  6187. * Returns a new Plane defined by the three passed points.
  6188. */
  6189. Plane.FromPoints = function (point1, point2, point3) {
  6190. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6191. result.copyFromPoints(point1, point2, point3);
  6192. return result;
  6193. };
  6194. /**
  6195. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6196. * Note : the vector "normal" is updated because normalized.
  6197. */
  6198. Plane.FromPositionAndNormal = function (origin, normal) {
  6199. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6200. normal.normalize();
  6201. result.normal = normal;
  6202. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6203. return result;
  6204. };
  6205. /**
  6206. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6207. */
  6208. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6209. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6210. return Vector3.Dot(point, normal) + d;
  6211. };
  6212. return Plane;
  6213. }());
  6214. BABYLON.Plane = Plane;
  6215. var Viewport = /** @class */ (function () {
  6216. /**
  6217. * Creates a Viewport object located at (x, y) and sized (width, height).
  6218. */
  6219. function Viewport(x, y, width, height) {
  6220. this.x = x;
  6221. this.y = y;
  6222. this.width = width;
  6223. this.height = height;
  6224. }
  6225. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6226. if (renderWidthOrEngine.getRenderWidth) {
  6227. var engine = renderWidthOrEngine;
  6228. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6229. }
  6230. var renderWidth = renderWidthOrEngine;
  6231. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6232. };
  6233. /**
  6234. * Returns a new Viewport copied from the current one.
  6235. */
  6236. Viewport.prototype.clone = function () {
  6237. return new Viewport(this.x, this.y, this.width, this.height);
  6238. };
  6239. return Viewport;
  6240. }());
  6241. BABYLON.Viewport = Viewport;
  6242. var Frustum = /** @class */ (function () {
  6243. function Frustum() {
  6244. }
  6245. /**
  6246. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6247. */
  6248. Frustum.GetPlanes = function (transform) {
  6249. var frustumPlanes = [];
  6250. for (var index = 0; index < 6; index++) {
  6251. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6252. }
  6253. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6254. return frustumPlanes;
  6255. };
  6256. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6257. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6258. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6259. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6260. frustumPlane.d = transform.m[15] + transform.m[14];
  6261. frustumPlane.normalize();
  6262. };
  6263. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6264. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6265. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6266. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6267. frustumPlane.d = transform.m[15] - transform.m[14];
  6268. frustumPlane.normalize();
  6269. };
  6270. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6271. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6272. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6273. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6274. frustumPlane.d = transform.m[15] + transform.m[12];
  6275. frustumPlane.normalize();
  6276. };
  6277. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6278. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6279. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6280. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6281. frustumPlane.d = transform.m[15] - transform.m[12];
  6282. frustumPlane.normalize();
  6283. };
  6284. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6285. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6286. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6287. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6288. frustumPlane.d = transform.m[15] - transform.m[13];
  6289. frustumPlane.normalize();
  6290. };
  6291. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6292. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6293. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6294. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6295. frustumPlane.d = transform.m[15] + transform.m[13];
  6296. frustumPlane.normalize();
  6297. };
  6298. /**
  6299. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6300. */
  6301. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6302. // Near
  6303. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6304. // Far
  6305. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6306. // Left
  6307. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6308. // Right
  6309. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6310. // Top
  6311. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6312. // Bottom
  6313. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6314. };
  6315. return Frustum;
  6316. }());
  6317. BABYLON.Frustum = Frustum;
  6318. var Space;
  6319. (function (Space) {
  6320. Space[Space["LOCAL"] = 0] = "LOCAL";
  6321. Space[Space["WORLD"] = 1] = "WORLD";
  6322. Space[Space["BONE"] = 2] = "BONE";
  6323. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6324. var Axis = /** @class */ (function () {
  6325. function Axis() {
  6326. }
  6327. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6328. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6329. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6330. return Axis;
  6331. }());
  6332. BABYLON.Axis = Axis;
  6333. ;
  6334. var BezierCurve = /** @class */ (function () {
  6335. function BezierCurve() {
  6336. }
  6337. /**
  6338. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6339. */
  6340. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6341. // Extract X (which is equal to time here)
  6342. var f0 = 1 - 3 * x2 + 3 * x1;
  6343. var f1 = 3 * x2 - 6 * x1;
  6344. var f2 = 3 * x1;
  6345. var refinedT = t;
  6346. for (var i = 0; i < 5; i++) {
  6347. var refinedT2 = refinedT * refinedT;
  6348. var refinedT3 = refinedT2 * refinedT;
  6349. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6350. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6351. refinedT -= (x - t) * slope;
  6352. refinedT = Math.min(1, Math.max(0, refinedT));
  6353. }
  6354. // Resolve cubic bezier for the given x
  6355. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6356. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6357. Math.pow(refinedT, 3);
  6358. };
  6359. return BezierCurve;
  6360. }());
  6361. BABYLON.BezierCurve = BezierCurve;
  6362. var Orientation;
  6363. (function (Orientation) {
  6364. Orientation[Orientation["CW"] = 0] = "CW";
  6365. Orientation[Orientation["CCW"] = 1] = "CCW";
  6366. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6367. var Angle = /** @class */ (function () {
  6368. /**
  6369. * Creates an Angle object of "radians" radians (float).
  6370. */
  6371. function Angle(radians) {
  6372. var _this = this;
  6373. /**
  6374. * Returns the Angle value in degrees (float).
  6375. */
  6376. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6377. /**
  6378. * Returns the Angle value in radians (float).
  6379. */
  6380. this.radians = function () { return _this._radians; };
  6381. this._radians = radians;
  6382. if (this._radians < 0.0)
  6383. this._radians += (2.0 * Math.PI);
  6384. }
  6385. /**
  6386. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6387. */
  6388. Angle.BetweenTwoPoints = function (a, b) {
  6389. var delta = b.subtract(a);
  6390. var theta = Math.atan2(delta.y, delta.x);
  6391. return new Angle(theta);
  6392. };
  6393. /**
  6394. * Returns a new Angle object from the passed float in radians.
  6395. */
  6396. Angle.FromRadians = function (radians) {
  6397. return new Angle(radians);
  6398. };
  6399. /**
  6400. * Returns a new Angle object from the passed float in degrees.
  6401. */
  6402. Angle.FromDegrees = function (degrees) {
  6403. return new Angle(degrees * Math.PI / 180.0);
  6404. };
  6405. return Angle;
  6406. }());
  6407. BABYLON.Angle = Angle;
  6408. var Arc2 = /** @class */ (function () {
  6409. /**
  6410. * Creates an Arc object from the three passed points : start, middle and end.
  6411. */
  6412. function Arc2(startPoint, midPoint, endPoint) {
  6413. this.startPoint = startPoint;
  6414. this.midPoint = midPoint;
  6415. this.endPoint = endPoint;
  6416. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6417. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6418. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6419. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6420. 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);
  6421. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6422. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6423. var a1 = this.startAngle.degrees();
  6424. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6425. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6426. // angles correction
  6427. if (a2 - a1 > +180.0)
  6428. a2 -= 360.0;
  6429. if (a2 - a1 < -180.0)
  6430. a2 += 360.0;
  6431. if (a3 - a2 > +180.0)
  6432. a3 -= 360.0;
  6433. if (a3 - a2 < -180.0)
  6434. a3 += 360.0;
  6435. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6436. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6437. }
  6438. return Arc2;
  6439. }());
  6440. BABYLON.Arc2 = Arc2;
  6441. var Path2 = /** @class */ (function () {
  6442. /**
  6443. * Creates a Path2 object from the starting 2D coordinates x and y.
  6444. */
  6445. function Path2(x, y) {
  6446. this._points = new Array();
  6447. this._length = 0.0;
  6448. this.closed = false;
  6449. this._points.push(new Vector2(x, y));
  6450. }
  6451. /**
  6452. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6453. * Returns the updated Path2.
  6454. */
  6455. Path2.prototype.addLineTo = function (x, y) {
  6456. if (this.closed) {
  6457. return this;
  6458. }
  6459. var newPoint = new Vector2(x, y);
  6460. var previousPoint = this._points[this._points.length - 1];
  6461. this._points.push(newPoint);
  6462. this._length += newPoint.subtract(previousPoint).length();
  6463. return this;
  6464. };
  6465. /**
  6466. * 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.
  6467. * Returns the updated Path2.
  6468. */
  6469. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6470. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6471. if (this.closed) {
  6472. return this;
  6473. }
  6474. var startPoint = this._points[this._points.length - 1];
  6475. var midPoint = new Vector2(midX, midY);
  6476. var endPoint = new Vector2(endX, endY);
  6477. var arc = new Arc2(startPoint, midPoint, endPoint);
  6478. var increment = arc.angle.radians() / numberOfSegments;
  6479. if (arc.orientation === Orientation.CW)
  6480. increment *= -1;
  6481. var currentAngle = arc.startAngle.radians() + increment;
  6482. for (var i = 0; i < numberOfSegments; i++) {
  6483. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6484. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6485. this.addLineTo(x, y);
  6486. currentAngle += increment;
  6487. }
  6488. return this;
  6489. };
  6490. /**
  6491. * Closes the Path2.
  6492. * Returns the Path2.
  6493. */
  6494. Path2.prototype.close = function () {
  6495. this.closed = true;
  6496. return this;
  6497. };
  6498. /**
  6499. * Returns the Path2 total length (float).
  6500. */
  6501. Path2.prototype.length = function () {
  6502. var result = this._length;
  6503. if (!this.closed) {
  6504. var lastPoint = this._points[this._points.length - 1];
  6505. var firstPoint = this._points[0];
  6506. result += (firstPoint.subtract(lastPoint).length());
  6507. }
  6508. return result;
  6509. };
  6510. /**
  6511. * Returns the Path2 internal array of points.
  6512. */
  6513. Path2.prototype.getPoints = function () {
  6514. return this._points;
  6515. };
  6516. /**
  6517. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6518. */
  6519. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6520. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6521. return Vector2.Zero();
  6522. }
  6523. var lengthPosition = normalizedLengthPosition * this.length();
  6524. var previousOffset = 0;
  6525. for (var i = 0; i < this._points.length; i++) {
  6526. var j = (i + 1) % this._points.length;
  6527. var a = this._points[i];
  6528. var b = this._points[j];
  6529. var bToA = b.subtract(a);
  6530. var nextOffset = (bToA.length() + previousOffset);
  6531. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6532. var dir = bToA.normalize();
  6533. var localOffset = lengthPosition - previousOffset;
  6534. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6535. }
  6536. previousOffset = nextOffset;
  6537. }
  6538. return Vector2.Zero();
  6539. };
  6540. /**
  6541. * Returns a new Path2 starting at the coordinates (x, y).
  6542. */
  6543. Path2.StartingAt = function (x, y) {
  6544. return new Path2(x, y);
  6545. };
  6546. return Path2;
  6547. }());
  6548. BABYLON.Path2 = Path2;
  6549. var Path3D = /** @class */ (function () {
  6550. /**
  6551. * new Path3D(path, normal, raw)
  6552. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6553. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6554. * path : an array of Vector3, the curve axis of the Path3D
  6555. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6556. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6557. */
  6558. function Path3D(path, firstNormal, raw) {
  6559. if (firstNormal === void 0) { firstNormal = null; }
  6560. this.path = path;
  6561. this._curve = new Array();
  6562. this._distances = new Array();
  6563. this._tangents = new Array();
  6564. this._normals = new Array();
  6565. this._binormals = new Array();
  6566. for (var p = 0; p < path.length; p++) {
  6567. this._curve[p] = path[p].clone(); // hard copy
  6568. }
  6569. this._raw = raw || false;
  6570. this._compute(firstNormal);
  6571. }
  6572. /**
  6573. * Returns the Path3D array of successive Vector3 designing its curve.
  6574. */
  6575. Path3D.prototype.getCurve = function () {
  6576. return this._curve;
  6577. };
  6578. /**
  6579. * Returns an array populated with tangent vectors on each Path3D curve point.
  6580. */
  6581. Path3D.prototype.getTangents = function () {
  6582. return this._tangents;
  6583. };
  6584. /**
  6585. * Returns an array populated with normal vectors on each Path3D curve point.
  6586. */
  6587. Path3D.prototype.getNormals = function () {
  6588. return this._normals;
  6589. };
  6590. /**
  6591. * Returns an array populated with binormal vectors on each Path3D curve point.
  6592. */
  6593. Path3D.prototype.getBinormals = function () {
  6594. return this._binormals;
  6595. };
  6596. /**
  6597. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6598. */
  6599. Path3D.prototype.getDistances = function () {
  6600. return this._distances;
  6601. };
  6602. /**
  6603. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6604. * Returns the same object updated.
  6605. */
  6606. Path3D.prototype.update = function (path, firstNormal) {
  6607. if (firstNormal === void 0) { firstNormal = null; }
  6608. for (var p = 0; p < path.length; p++) {
  6609. this._curve[p].x = path[p].x;
  6610. this._curve[p].y = path[p].y;
  6611. this._curve[p].z = path[p].z;
  6612. }
  6613. this._compute(firstNormal);
  6614. return this;
  6615. };
  6616. // private function compute() : computes tangents, normals and binormals
  6617. Path3D.prototype._compute = function (firstNormal) {
  6618. var l = this._curve.length;
  6619. // first and last tangents
  6620. this._tangents[0] = this._getFirstNonNullVector(0);
  6621. if (!this._raw) {
  6622. this._tangents[0].normalize();
  6623. }
  6624. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6625. if (!this._raw) {
  6626. this._tangents[l - 1].normalize();
  6627. }
  6628. // normals and binormals at first point : arbitrary vector with _normalVector()
  6629. var tg0 = this._tangents[0];
  6630. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6631. this._normals[0] = pp0;
  6632. if (!this._raw) {
  6633. this._normals[0].normalize();
  6634. }
  6635. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6636. if (!this._raw) {
  6637. this._binormals[0].normalize();
  6638. }
  6639. this._distances[0] = 0.0;
  6640. // normals and binormals : next points
  6641. var prev; // previous vector (segment)
  6642. var cur; // current vector (segment)
  6643. var curTang; // current tangent
  6644. // previous normal
  6645. var prevBinor; // previous binormal
  6646. for (var i = 1; i < l; i++) {
  6647. // tangents
  6648. prev = this._getLastNonNullVector(i);
  6649. if (i < l - 1) {
  6650. cur = this._getFirstNonNullVector(i);
  6651. this._tangents[i] = prev.add(cur);
  6652. this._tangents[i].normalize();
  6653. }
  6654. this._distances[i] = this._distances[i - 1] + prev.length();
  6655. // normals and binormals
  6656. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6657. curTang = this._tangents[i];
  6658. prevBinor = this._binormals[i - 1];
  6659. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6660. if (!this._raw) {
  6661. this._normals[i].normalize();
  6662. }
  6663. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6664. if (!this._raw) {
  6665. this._binormals[i].normalize();
  6666. }
  6667. }
  6668. };
  6669. // private function getFirstNonNullVector(index)
  6670. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6671. Path3D.prototype._getFirstNonNullVector = function (index) {
  6672. var i = 1;
  6673. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6674. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6675. i++;
  6676. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6677. }
  6678. return nNVector;
  6679. };
  6680. // private function getLastNonNullVector(index)
  6681. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6682. Path3D.prototype._getLastNonNullVector = function (index) {
  6683. var i = 1;
  6684. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6685. while (nLVector.length() === 0 && index > i + 1) {
  6686. i++;
  6687. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6688. }
  6689. return nLVector;
  6690. };
  6691. // private function normalVector(v0, vt, va) :
  6692. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6693. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6694. Path3D.prototype._normalVector = function (v0, vt, va) {
  6695. var normal0;
  6696. var tgl = vt.length();
  6697. if (tgl === 0.0) {
  6698. tgl = 1.0;
  6699. }
  6700. if (va === undefined || va === null) {
  6701. var point;
  6702. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6703. point = new Vector3(0.0, -1.0, 0.0);
  6704. }
  6705. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6706. point = new Vector3(1.0, 0.0, 0.0);
  6707. }
  6708. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6709. point = new Vector3(0.0, 0.0, 1.0);
  6710. }
  6711. else {
  6712. point = Vector3.Zero();
  6713. }
  6714. normal0 = Vector3.Cross(vt, point);
  6715. }
  6716. else {
  6717. normal0 = Vector3.Cross(vt, va);
  6718. Vector3.CrossToRef(normal0, vt, normal0);
  6719. }
  6720. normal0.normalize();
  6721. return normal0;
  6722. };
  6723. return Path3D;
  6724. }());
  6725. BABYLON.Path3D = Path3D;
  6726. var Curve3 = /** @class */ (function () {
  6727. /**
  6728. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6729. * A Curve3 is designed from a series of successive Vector3.
  6730. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6731. */
  6732. function Curve3(points) {
  6733. this._length = 0.0;
  6734. this._points = points;
  6735. this._length = this._computeLength(points);
  6736. }
  6737. /**
  6738. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6739. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6740. * @param v1 (Vector3) the control point
  6741. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6742. * @param nbPoints (integer) the wanted number of points in the curve
  6743. */
  6744. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6745. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6746. var bez = new Array();
  6747. var equation = function (t, val0, val1, val2) {
  6748. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6749. return res;
  6750. };
  6751. for (var i = 0; i <= nbPoints; i++) {
  6752. 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)));
  6753. }
  6754. return new Curve3(bez);
  6755. };
  6756. /**
  6757. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6758. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6759. * @param v1 (Vector3) the first control point
  6760. * @param v2 (Vector3) the second control point
  6761. * @param v3 (Vector3) the end point of the Cubic Bezier
  6762. * @param nbPoints (integer) the wanted number of points in the curve
  6763. */
  6764. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6765. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6766. var bez = new Array();
  6767. var equation = function (t, val0, val1, val2, val3) {
  6768. 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;
  6769. return res;
  6770. };
  6771. for (var i = 0; i <= nbPoints; i++) {
  6772. 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)));
  6773. }
  6774. return new Curve3(bez);
  6775. };
  6776. /**
  6777. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6778. * @param p1 (Vector3) the origin point of the Hermite Spline
  6779. * @param t1 (Vector3) the tangent vector at the origin point
  6780. * @param p2 (Vector3) the end point of the Hermite Spline
  6781. * @param t2 (Vector3) the tangent vector at the end point
  6782. * @param nbPoints (integer) the wanted number of points in the curve
  6783. */
  6784. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6785. var hermite = new Array();
  6786. var step = 1.0 / nbPoints;
  6787. for (var i = 0; i <= nbPoints; i++) {
  6788. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6789. }
  6790. return new Curve3(hermite);
  6791. };
  6792. /**
  6793. * Returns a Curve3 object along a CatmullRom Spline curve :
  6794. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6795. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6796. */
  6797. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6798. var totalPoints = new Array();
  6799. totalPoints.push(points[0].clone());
  6800. Array.prototype.push.apply(totalPoints, points);
  6801. totalPoints.push(points[points.length - 1].clone());
  6802. var catmullRom = new Array();
  6803. var step = 1.0 / nbPoints;
  6804. var amount = 0.0;
  6805. for (var i = 0; i < totalPoints.length - 3; i++) {
  6806. amount = 0;
  6807. for (var c = 0; c < nbPoints; c++) {
  6808. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6809. amount += step;
  6810. }
  6811. }
  6812. i--;
  6813. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6814. return new Curve3(catmullRom);
  6815. };
  6816. /**
  6817. * Returns the Curve3 stored array of successive Vector3
  6818. */
  6819. Curve3.prototype.getPoints = function () {
  6820. return this._points;
  6821. };
  6822. /**
  6823. * Returns the computed length (float) of the curve.
  6824. */
  6825. Curve3.prototype.length = function () {
  6826. return this._length;
  6827. };
  6828. /**
  6829. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6830. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6831. * curveA and curveB keep unchanged.
  6832. */
  6833. Curve3.prototype.continue = function (curve) {
  6834. var lastPoint = this._points[this._points.length - 1];
  6835. var continuedPoints = this._points.slice();
  6836. var curvePoints = curve.getPoints();
  6837. for (var i = 1; i < curvePoints.length; i++) {
  6838. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6839. }
  6840. var continuedCurve = new Curve3(continuedPoints);
  6841. return continuedCurve;
  6842. };
  6843. Curve3.prototype._computeLength = function (path) {
  6844. var l = 0;
  6845. for (var i = 1; i < path.length; i++) {
  6846. l += (path[i].subtract(path[i - 1])).length();
  6847. }
  6848. return l;
  6849. };
  6850. return Curve3;
  6851. }());
  6852. BABYLON.Curve3 = Curve3;
  6853. // Vertex formats
  6854. var PositionNormalVertex = /** @class */ (function () {
  6855. function PositionNormalVertex(position, normal) {
  6856. if (position === void 0) { position = Vector3.Zero(); }
  6857. if (normal === void 0) { normal = Vector3.Up(); }
  6858. this.position = position;
  6859. this.normal = normal;
  6860. }
  6861. PositionNormalVertex.prototype.clone = function () {
  6862. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6863. };
  6864. return PositionNormalVertex;
  6865. }());
  6866. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6867. var PositionNormalTextureVertex = /** @class */ (function () {
  6868. function PositionNormalTextureVertex(position, normal, uv) {
  6869. if (position === void 0) { position = Vector3.Zero(); }
  6870. if (normal === void 0) { normal = Vector3.Up(); }
  6871. if (uv === void 0) { uv = Vector2.Zero(); }
  6872. this.position = position;
  6873. this.normal = normal;
  6874. this.uv = uv;
  6875. }
  6876. PositionNormalTextureVertex.prototype.clone = function () {
  6877. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6878. };
  6879. return PositionNormalTextureVertex;
  6880. }());
  6881. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6882. // Temporary pre-allocated objects for engine internal use
  6883. // usage in any internal function :
  6884. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6885. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6886. var Tmp = /** @class */ (function () {
  6887. function Tmp() {
  6888. }
  6889. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6890. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6891. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6892. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6893. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6894. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6895. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6896. Matrix.Zero(), Matrix.Zero(),
  6897. Matrix.Zero(), Matrix.Zero(),
  6898. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6899. return Tmp;
  6900. }());
  6901. BABYLON.Tmp = Tmp;
  6902. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6903. var MathTmp = /** @class */ (function () {
  6904. function MathTmp() {
  6905. }
  6906. MathTmp.Vector3 = [Vector3.Zero()];
  6907. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6908. MathTmp.Quaternion = [Quaternion.Zero()];
  6909. return MathTmp;
  6910. }());
  6911. })(BABYLON || (BABYLON = {}));
  6912. //# sourceMappingURL=babylon.math.js.map
  6913. "use strict";
  6914. var BABYLON;
  6915. (function (BABYLON) {
  6916. var Scalar = /** @class */ (function () {
  6917. function Scalar() {
  6918. }
  6919. /**
  6920. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6921. */
  6922. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6923. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6924. var num = a - b;
  6925. return -epsilon <= num && num <= epsilon;
  6926. };
  6927. /**
  6928. * Returns a string : the upper case translation of the number i to hexadecimal.
  6929. */
  6930. Scalar.ToHex = function (i) {
  6931. var str = i.toString(16);
  6932. if (i <= 15) {
  6933. return ("0" + str).toUpperCase();
  6934. }
  6935. return str.toUpperCase();
  6936. };
  6937. /**
  6938. * Returns -1 if value is negative and +1 is value is positive.
  6939. * Returns the value itself if it's equal to zero.
  6940. */
  6941. Scalar.Sign = function (value) {
  6942. value = +value; // convert to a number
  6943. if (value === 0 || isNaN(value))
  6944. return value;
  6945. return value > 0 ? 1 : -1;
  6946. };
  6947. /**
  6948. * Returns the value itself if it's between min and max.
  6949. * Returns min if the value is lower than min.
  6950. * Returns max if the value is greater than max.
  6951. */
  6952. Scalar.Clamp = function (value, min, max) {
  6953. if (min === void 0) { min = 0; }
  6954. if (max === void 0) { max = 1; }
  6955. return Math.min(max, Math.max(min, value));
  6956. };
  6957. /**
  6958. * Returns the log2 of value.
  6959. */
  6960. Scalar.Log2 = function (value) {
  6961. return Math.log(value) * Math.LOG2E;
  6962. };
  6963. /**
  6964. * Loops the value, so that it is never larger than length and never smaller than 0.
  6965. *
  6966. * This is similar to the modulo operator but it works with floating point numbers.
  6967. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6968. * With t = 5 and length = 2.5, the result would be 0.0.
  6969. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6970. */
  6971. Scalar.Repeat = function (value, length) {
  6972. return value - Math.floor(value / length) * length;
  6973. };
  6974. /**
  6975. * Normalize the value between 0.0 and 1.0 using min and max values
  6976. */
  6977. Scalar.Normalize = function (value, min, max) {
  6978. return (value - min) / (max - min);
  6979. };
  6980. /**
  6981. * Denormalize the value from 0.0 and 1.0 using min and max values
  6982. */
  6983. Scalar.Denormalize = function (normalized, min, max) {
  6984. return (normalized * (max - min) + min);
  6985. };
  6986. /**
  6987. * Calculates the shortest difference between two given angles given in degrees.
  6988. */
  6989. Scalar.DeltaAngle = function (current, target) {
  6990. var num = Scalar.Repeat(target - current, 360.0);
  6991. if (num > 180.0) {
  6992. num -= 360.0;
  6993. }
  6994. return num;
  6995. };
  6996. /**
  6997. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6998. *
  6999. * The returned value will move back and forth between 0 and length
  7000. */
  7001. Scalar.PingPong = function (tx, length) {
  7002. var t = Scalar.Repeat(tx, length * 2.0);
  7003. return length - Math.abs(t - length);
  7004. };
  7005. /**
  7006. * Interpolates between min and max with smoothing at the limits.
  7007. *
  7008. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7009. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7010. */
  7011. Scalar.SmoothStep = function (from, to, tx) {
  7012. var t = Scalar.Clamp(tx);
  7013. t = -2.0 * t * t * t + 3.0 * t * t;
  7014. return to * t + from * (1.0 - t);
  7015. };
  7016. /**
  7017. * Moves a value current towards target.
  7018. *
  7019. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7020. * Negative values of maxDelta pushes the value away from target.
  7021. */
  7022. Scalar.MoveTowards = function (current, target, maxDelta) {
  7023. var result = 0;
  7024. if (Math.abs(target - current) <= maxDelta) {
  7025. result = target;
  7026. }
  7027. else {
  7028. result = current + Scalar.Sign(target - current) * maxDelta;
  7029. }
  7030. return result;
  7031. };
  7032. /**
  7033. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7034. *
  7035. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7036. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7037. */
  7038. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7039. var num = Scalar.DeltaAngle(current, target);
  7040. var result = 0;
  7041. if (-maxDelta < num && num < maxDelta) {
  7042. result = target;
  7043. }
  7044. else {
  7045. target = current + num;
  7046. result = Scalar.MoveTowards(current, target, maxDelta);
  7047. }
  7048. return result;
  7049. };
  7050. /**
  7051. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7052. */
  7053. Scalar.Lerp = function (start, end, amount) {
  7054. return start + ((end - start) * amount);
  7055. };
  7056. /**
  7057. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7058. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7059. */
  7060. Scalar.LerpAngle = function (start, end, amount) {
  7061. var num = Scalar.Repeat(end - start, 360.0);
  7062. if (num > 180.0) {
  7063. num -= 360.0;
  7064. }
  7065. return start + num * Scalar.Clamp(amount);
  7066. };
  7067. /**
  7068. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7069. */
  7070. Scalar.InverseLerp = function (a, b, value) {
  7071. var result = 0;
  7072. if (a != b) {
  7073. result = Scalar.Clamp((value - a) / (b - a));
  7074. }
  7075. else {
  7076. result = 0.0;
  7077. }
  7078. return result;
  7079. };
  7080. /**
  7081. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7082. */
  7083. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7084. var squared = amount * amount;
  7085. var cubed = amount * squared;
  7086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7088. var part3 = (cubed - (2.0 * squared)) + amount;
  7089. var part4 = cubed - squared;
  7090. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7091. };
  7092. /**
  7093. * Returns a random float number between and min and max values
  7094. */
  7095. Scalar.RandomRange = function (min, max) {
  7096. if (min === max)
  7097. return min;
  7098. return ((Math.random() * (max - min)) + min);
  7099. };
  7100. /**
  7101. * This function returns percentage of a number in a given range.
  7102. *
  7103. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7104. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7105. */
  7106. Scalar.RangeToPercent = function (number, min, max) {
  7107. return ((number - min) / (max - min));
  7108. };
  7109. /**
  7110. * This function returns number that corresponds to the percentage in a given range.
  7111. *
  7112. * PercentToRange(0.34,0,100) will return 34.
  7113. */
  7114. Scalar.PercentToRange = function (percent, min, max) {
  7115. return ((max - min) * percent + min);
  7116. };
  7117. /**
  7118. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7119. * @param angle The angle to normalize in radian.
  7120. * @return The converted angle.
  7121. */
  7122. Scalar.NormalizeRadians = function (angle) {
  7123. // More precise but slower version kept for reference.
  7124. // angle = angle % Tools.TwoPi;
  7125. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7126. //if (angle > Math.PI) {
  7127. // angle -= Tools.TwoPi;
  7128. //}
  7129. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7130. return angle;
  7131. };
  7132. /**
  7133. * Two pi constants convenient for computation.
  7134. */
  7135. Scalar.TwoPi = Math.PI * 2;
  7136. return Scalar;
  7137. }());
  7138. BABYLON.Scalar = Scalar;
  7139. })(BABYLON || (BABYLON = {}));
  7140. //# sourceMappingURL=babylon.math.scalar.js.map
  7141. "use strict";
  7142. //# sourceMappingURL=babylon.mixins.js.map
  7143. "use strict";
  7144. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7145. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7146. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7147. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7148. //# sourceMappingURL=babylon.webgl2.js.map
  7149. "use strict";
  7150. var BABYLON;
  7151. (function (BABYLON) {
  7152. var __decoratorInitialStore = {};
  7153. var __mergedStore = {};
  7154. var _copySource = function (creationFunction, source, instanciate) {
  7155. var destination = creationFunction();
  7156. // Tags
  7157. if (BABYLON.Tags) {
  7158. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7159. }
  7160. var classStore = getMergedStore(destination);
  7161. // Properties
  7162. for (var property in classStore) {
  7163. var propertyDescriptor = classStore[property];
  7164. var sourceProperty = source[property];
  7165. var propertyType = propertyDescriptor.type;
  7166. if (sourceProperty !== undefined && sourceProperty !== null) {
  7167. switch (propertyType) {
  7168. case 0: // Value
  7169. case 6: // Mesh reference
  7170. case 11:// Camera reference
  7171. destination[property] = sourceProperty;
  7172. break;
  7173. case 1:// Texture
  7174. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7175. break;
  7176. case 2: // Color3
  7177. case 3: // FresnelParameters
  7178. case 4: // Vector2
  7179. case 5: // Vector3
  7180. case 7: // Color Curves
  7181. case 10:// Quaternion
  7182. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7183. break;
  7184. }
  7185. }
  7186. }
  7187. return destination;
  7188. };
  7189. function getDirectStore(target) {
  7190. var classKey = target.getClassName();
  7191. if (!__decoratorInitialStore[classKey]) {
  7192. __decoratorInitialStore[classKey] = {};
  7193. }
  7194. return __decoratorInitialStore[classKey];
  7195. }
  7196. /**
  7197. * Return the list of properties flagged as serializable
  7198. * @param target: host object
  7199. */
  7200. function getMergedStore(target) {
  7201. var classKey = target.getClassName();
  7202. if (__mergedStore[classKey]) {
  7203. return __mergedStore[classKey];
  7204. }
  7205. __mergedStore[classKey] = {};
  7206. var store = __mergedStore[classKey];
  7207. var currentTarget = target;
  7208. var currentKey = classKey;
  7209. while (currentKey) {
  7210. var initialStore = __decoratorInitialStore[currentKey];
  7211. for (var property in initialStore) {
  7212. store[property] = initialStore[property];
  7213. }
  7214. var parent_1 = void 0;
  7215. var done = false;
  7216. do {
  7217. parent_1 = Object.getPrototypeOf(currentTarget);
  7218. if (!parent_1.getClassName) {
  7219. done = true;
  7220. break;
  7221. }
  7222. if (parent_1.getClassName() !== currentKey) {
  7223. break;
  7224. }
  7225. currentTarget = parent_1;
  7226. } while (parent_1);
  7227. if (done) {
  7228. break;
  7229. }
  7230. currentKey = parent_1.getClassName();
  7231. currentTarget = parent_1;
  7232. }
  7233. return store;
  7234. }
  7235. function generateSerializableMember(type, sourceName) {
  7236. return function (target, propertyKey) {
  7237. var classStore = getDirectStore(target);
  7238. if (!classStore[propertyKey]) {
  7239. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7240. }
  7241. };
  7242. }
  7243. function generateExpandMember(setCallback, targetKey) {
  7244. if (targetKey === void 0) { targetKey = null; }
  7245. return function (target, propertyKey) {
  7246. var key = targetKey || ("_" + propertyKey);
  7247. Object.defineProperty(target, propertyKey, {
  7248. get: function () {
  7249. return this[key];
  7250. },
  7251. set: function (value) {
  7252. if (this[key] === value) {
  7253. return;
  7254. }
  7255. this[key] = value;
  7256. target[setCallback].apply(this);
  7257. },
  7258. enumerable: true,
  7259. configurable: true
  7260. });
  7261. };
  7262. }
  7263. function expandToProperty(callback, targetKey) {
  7264. if (targetKey === void 0) { targetKey = null; }
  7265. return generateExpandMember(callback, targetKey);
  7266. }
  7267. BABYLON.expandToProperty = expandToProperty;
  7268. function serialize(sourceName) {
  7269. return generateSerializableMember(0, sourceName); // value member
  7270. }
  7271. BABYLON.serialize = serialize;
  7272. function serializeAsTexture(sourceName) {
  7273. return generateSerializableMember(1, sourceName); // texture member
  7274. }
  7275. BABYLON.serializeAsTexture = serializeAsTexture;
  7276. function serializeAsColor3(sourceName) {
  7277. return generateSerializableMember(2, sourceName); // color3 member
  7278. }
  7279. BABYLON.serializeAsColor3 = serializeAsColor3;
  7280. function serializeAsFresnelParameters(sourceName) {
  7281. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7282. }
  7283. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7284. function serializeAsVector2(sourceName) {
  7285. return generateSerializableMember(4, sourceName); // vector2 member
  7286. }
  7287. BABYLON.serializeAsVector2 = serializeAsVector2;
  7288. function serializeAsVector3(sourceName) {
  7289. return generateSerializableMember(5, sourceName); // vector3 member
  7290. }
  7291. BABYLON.serializeAsVector3 = serializeAsVector3;
  7292. function serializeAsMeshReference(sourceName) {
  7293. return generateSerializableMember(6, sourceName); // mesh reference member
  7294. }
  7295. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7296. function serializeAsColorCurves(sourceName) {
  7297. return generateSerializableMember(7, sourceName); // color curves
  7298. }
  7299. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7300. function serializeAsColor4(sourceName) {
  7301. return generateSerializableMember(8, sourceName); // color 4
  7302. }
  7303. BABYLON.serializeAsColor4 = serializeAsColor4;
  7304. function serializeAsImageProcessingConfiguration(sourceName) {
  7305. return generateSerializableMember(9, sourceName); // image processing
  7306. }
  7307. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7308. function serializeAsQuaternion(sourceName) {
  7309. return generateSerializableMember(10, sourceName); // quaternion member
  7310. }
  7311. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7312. /**
  7313. * Decorator used to define property that can be serialized as reference to a camera
  7314. * @param sourceName defines the name of the property to decorate
  7315. */
  7316. function serializeAsCameraReference(sourceName) {
  7317. return generateSerializableMember(11, sourceName); // camera reference member
  7318. }
  7319. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7320. var SerializationHelper = /** @class */ (function () {
  7321. function SerializationHelper() {
  7322. }
  7323. SerializationHelper.Serialize = function (entity, serializationObject) {
  7324. if (!serializationObject) {
  7325. serializationObject = {};
  7326. }
  7327. // Tags
  7328. if (BABYLON.Tags) {
  7329. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7330. }
  7331. var serializedProperties = getMergedStore(entity);
  7332. // Properties
  7333. for (var property in serializedProperties) {
  7334. var propertyDescriptor = serializedProperties[property];
  7335. var targetPropertyName = propertyDescriptor.sourceName || property;
  7336. var propertyType = propertyDescriptor.type;
  7337. var sourceProperty = entity[property];
  7338. if (sourceProperty !== undefined && sourceProperty !== null) {
  7339. switch (propertyType) {
  7340. case 0:// Value
  7341. serializationObject[targetPropertyName] = sourceProperty;
  7342. break;
  7343. case 1:// Texture
  7344. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7345. break;
  7346. case 2:// Color3
  7347. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7348. break;
  7349. case 3:// FresnelParameters
  7350. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7351. break;
  7352. case 4:// Vector2
  7353. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7354. break;
  7355. case 5:// Vector3
  7356. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7357. break;
  7358. case 6:// Mesh reference
  7359. serializationObject[targetPropertyName] = sourceProperty.id;
  7360. break;
  7361. case 7:// Color Curves
  7362. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7363. break;
  7364. case 8:// Color 4
  7365. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7366. break;
  7367. case 9:// Image Processing
  7368. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7369. break;
  7370. case 10:// Quaternion
  7371. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7372. break;
  7373. case 11:// Camera reference
  7374. serializationObject[targetPropertyName] = sourceProperty.id;
  7375. break;
  7376. }
  7377. }
  7378. }
  7379. return serializationObject;
  7380. };
  7381. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7382. if (rootUrl === void 0) { rootUrl = null; }
  7383. var destination = creationFunction();
  7384. if (!rootUrl) {
  7385. rootUrl = "";
  7386. }
  7387. // Tags
  7388. if (BABYLON.Tags) {
  7389. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7390. }
  7391. var classStore = getMergedStore(destination);
  7392. // Properties
  7393. for (var property in classStore) {
  7394. var propertyDescriptor = classStore[property];
  7395. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7396. var propertyType = propertyDescriptor.type;
  7397. if (sourceProperty !== undefined && sourceProperty !== null) {
  7398. var dest = destination;
  7399. switch (propertyType) {
  7400. case 0:// Value
  7401. dest[property] = sourceProperty;
  7402. break;
  7403. case 1:// Texture
  7404. if (scene) {
  7405. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7406. }
  7407. break;
  7408. case 2:// Color3
  7409. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7410. break;
  7411. case 3:// FresnelParameters
  7412. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7413. break;
  7414. case 4:// Vector2
  7415. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7416. break;
  7417. case 5:// Vector3
  7418. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7419. break;
  7420. case 6:// Mesh reference
  7421. if (scene) {
  7422. dest[property] = scene.getLastMeshByID(sourceProperty);
  7423. }
  7424. break;
  7425. case 7:// Color Curves
  7426. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7427. break;
  7428. case 8:// Color 4
  7429. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7430. break;
  7431. case 9:// Image Processing
  7432. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7433. break;
  7434. case 10:// Quaternion
  7435. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7436. break;
  7437. case 11:// Camera reference
  7438. if (scene) {
  7439. dest[property] = scene.getCameraByID(sourceProperty);
  7440. }
  7441. break;
  7442. }
  7443. }
  7444. }
  7445. return destination;
  7446. };
  7447. SerializationHelper.Clone = function (creationFunction, source) {
  7448. return _copySource(creationFunction, source, false);
  7449. };
  7450. SerializationHelper.Instanciate = function (creationFunction, source) {
  7451. return _copySource(creationFunction, source, true);
  7452. };
  7453. return SerializationHelper;
  7454. }());
  7455. BABYLON.SerializationHelper = SerializationHelper;
  7456. })(BABYLON || (BABYLON = {}));
  7457. //# sourceMappingURL=babylon.decorators.js.map
  7458. "use strict";
  7459. var BABYLON;
  7460. (function (BABYLON) {
  7461. /**
  7462. * Wrapper class for promise with external resolve and reject.
  7463. */
  7464. var Deferred = /** @class */ (function () {
  7465. /**
  7466. * Constructor for this deferred object.
  7467. */
  7468. function Deferred() {
  7469. var _this = this;
  7470. this.promise = new Promise(function (resolve, reject) {
  7471. _this._resolve = resolve;
  7472. _this._reject = reject;
  7473. });
  7474. }
  7475. Object.defineProperty(Deferred.prototype, "resolve", {
  7476. /**
  7477. * The resolve method of the promise associated with this deferred object.
  7478. */
  7479. get: function () {
  7480. return this._resolve;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(Deferred.prototype, "reject", {
  7486. /**
  7487. * The reject method of the promise associated with this deferred object.
  7488. */
  7489. get: function () {
  7490. return this._reject;
  7491. },
  7492. enumerable: true,
  7493. configurable: true
  7494. });
  7495. return Deferred;
  7496. }());
  7497. BABYLON.Deferred = Deferred;
  7498. })(BABYLON || (BABYLON = {}));
  7499. //# sourceMappingURL=babylon.deferred.js.map
  7500. "use strict";
  7501. var BABYLON;
  7502. (function (BABYLON) {
  7503. /**
  7504. * A class serves as a medium between the observable and its observers
  7505. */
  7506. var EventState = /** @class */ (function () {
  7507. /**
  7508. * Create a new EventState
  7509. * @param mask defines the mask associated with this state
  7510. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7511. * @param target defines the original target of the state
  7512. * @param currentTarget defines the current target of the state
  7513. */
  7514. function EventState(mask, skipNextObservers, target, currentTarget) {
  7515. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7516. this.initalize(mask, skipNextObservers, target, currentTarget);
  7517. }
  7518. /**
  7519. * Initialize the current event state
  7520. * @param mask defines the mask associated with this state
  7521. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7522. * @param target defines the original target of the state
  7523. * @param currentTarget defines the current target of the state
  7524. * @returns the current event state
  7525. */
  7526. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7527. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7528. this.mask = mask;
  7529. this.skipNextObservers = skipNextObservers;
  7530. this.target = target;
  7531. this.currentTarget = currentTarget;
  7532. return this;
  7533. };
  7534. return EventState;
  7535. }());
  7536. BABYLON.EventState = EventState;
  7537. /**
  7538. * Represent an Observer registered to a given Observable object.
  7539. */
  7540. var Observer = /** @class */ (function () {
  7541. /**
  7542. * Creates a new observer
  7543. * @param callback defines the callback to call when the observer is notified
  7544. * @param mask defines the mask of the observer (used to filter notifications)
  7545. * @param scope defines the current scope used to restore the JS context
  7546. */
  7547. function Observer(
  7548. /**
  7549. * Defines the callback to call when the observer is notified
  7550. */
  7551. callback,
  7552. /**
  7553. * Defines the mask of the observer (used to filter notifications)
  7554. */
  7555. mask,
  7556. /**
  7557. * Defines the current scope used to restore the JS context
  7558. */
  7559. scope) {
  7560. if (scope === void 0) { scope = null; }
  7561. this.callback = callback;
  7562. this.mask = mask;
  7563. this.scope = scope;
  7564. /** @ignore */
  7565. this._willBeUnregistered = false;
  7566. /**
  7567. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7568. */
  7569. this.unregisterOnNextCall = false;
  7570. }
  7571. return Observer;
  7572. }());
  7573. BABYLON.Observer = Observer;
  7574. /**
  7575. * Represent a list of observers registered to multiple Observables object.
  7576. */
  7577. var MultiObserver = /** @class */ (function () {
  7578. function MultiObserver() {
  7579. }
  7580. /**
  7581. * Release associated resources
  7582. */
  7583. MultiObserver.prototype.dispose = function () {
  7584. if (this._observers && this._observables) {
  7585. for (var index = 0; index < this._observers.length; index++) {
  7586. this._observables[index].remove(this._observers[index]);
  7587. }
  7588. }
  7589. this._observers = null;
  7590. this._observables = null;
  7591. };
  7592. /**
  7593. * Raise a callback when one of the observable will notify
  7594. * @param observables defines a list of observables to watch
  7595. * @param callback defines the callback to call on notification
  7596. * @param mask defines the mask used to filter notifications
  7597. * @param scope defines the current scope used to restore the JS context
  7598. * @returns the new MultiObserver
  7599. */
  7600. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7601. if (mask === void 0) { mask = -1; }
  7602. if (scope === void 0) { scope = null; }
  7603. var result = new MultiObserver();
  7604. result._observers = new Array();
  7605. result._observables = observables;
  7606. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7607. var observable = observables_1[_i];
  7608. var observer = observable.add(callback, mask, false, scope);
  7609. if (observer) {
  7610. result._observers.push(observer);
  7611. }
  7612. }
  7613. return result;
  7614. };
  7615. return MultiObserver;
  7616. }());
  7617. BABYLON.MultiObserver = MultiObserver;
  7618. /**
  7619. * The Observable class is a simple implementation of the Observable pattern.
  7620. *
  7621. * 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.
  7622. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7623. * 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).
  7624. * 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.
  7625. */
  7626. var Observable = /** @class */ (function () {
  7627. /**
  7628. * Creates a new observable
  7629. * @param onObserverAdded defines a callback to call when a new observer is added
  7630. */
  7631. function Observable(onObserverAdded) {
  7632. this._observers = new Array();
  7633. this._eventState = new EventState(0);
  7634. if (onObserverAdded) {
  7635. this._onObserverAdded = onObserverAdded;
  7636. }
  7637. }
  7638. /**
  7639. * Create a new Observer with the specified callback
  7640. * @param callback the callback that will be executed for that Observer
  7641. * @param mask the mask used to filter observers
  7642. * @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.
  7643. * @param scope optional scope for the callback to be called from
  7644. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7645. * @returns the new observer created for the callback
  7646. */
  7647. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7648. if (mask === void 0) { mask = -1; }
  7649. if (insertFirst === void 0) { insertFirst = false; }
  7650. if (scope === void 0) { scope = null; }
  7651. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7652. if (!callback) {
  7653. return null;
  7654. }
  7655. var observer = new Observer(callback, mask, scope);
  7656. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7657. if (insertFirst) {
  7658. this._observers.unshift(observer);
  7659. }
  7660. else {
  7661. this._observers.push(observer);
  7662. }
  7663. if (this._onObserverAdded) {
  7664. this._onObserverAdded(observer);
  7665. }
  7666. return observer;
  7667. };
  7668. /**
  7669. * Remove an Observer from the Observable object
  7670. * @param observer the instance of the Observer to remove
  7671. * @returns false if it doesn't belong to this Observable
  7672. */
  7673. Observable.prototype.remove = function (observer) {
  7674. if (!observer) {
  7675. return false;
  7676. }
  7677. var index = this._observers.indexOf(observer);
  7678. if (index !== -1) {
  7679. this._observers.splice(index, 1);
  7680. return true;
  7681. }
  7682. return false;
  7683. };
  7684. /**
  7685. * Remove a callback from the Observable object
  7686. * @param callback the callback to remove
  7687. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7688. * @returns false if it doesn't belong to this Observable
  7689. */
  7690. Observable.prototype.removeCallback = function (callback, scope) {
  7691. for (var index = 0; index < this._observers.length; index++) {
  7692. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7693. this._observers.splice(index, 1);
  7694. return true;
  7695. }
  7696. }
  7697. return false;
  7698. };
  7699. Observable.prototype._deferUnregister = function (observer) {
  7700. var _this = this;
  7701. observer.unregisterOnNextCall = false;
  7702. observer._willBeUnregistered = true;
  7703. BABYLON.Tools.SetImmediate(function () {
  7704. _this.remove(observer);
  7705. });
  7706. };
  7707. /**
  7708. * Notify all Observers by calling their respective callback with the given data
  7709. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7710. * @param eventData defines the data to send to all observers
  7711. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7712. * @param target defines the original target of the state
  7713. * @param currentTarget defines the current target of the state
  7714. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7715. */
  7716. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7717. if (mask === void 0) { mask = -1; }
  7718. if (!this._observers.length) {
  7719. return true;
  7720. }
  7721. var state = this._eventState;
  7722. state.mask = mask;
  7723. state.target = target;
  7724. state.currentTarget = currentTarget;
  7725. state.skipNextObservers = false;
  7726. state.lastReturnValue = eventData;
  7727. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7728. var obs = _a[_i];
  7729. if (obs._willBeUnregistered) {
  7730. continue;
  7731. }
  7732. if (obs.mask & mask) {
  7733. if (obs.scope) {
  7734. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7735. }
  7736. else {
  7737. state.lastReturnValue = obs.callback(eventData, state);
  7738. }
  7739. if (obs.unregisterOnNextCall) {
  7740. this._deferUnregister(obs);
  7741. }
  7742. }
  7743. if (state.skipNextObservers) {
  7744. return false;
  7745. }
  7746. }
  7747. return true;
  7748. };
  7749. /**
  7750. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7751. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7752. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7753. * and it is crucial that all callbacks will be executed.
  7754. * The order of the callbacks is kept, callbacks are not executed parallel.
  7755. *
  7756. * @param eventData The data to be sent to each callback
  7757. * @param mask is used to filter observers defaults to -1
  7758. * @param target defines the callback target (see EventState)
  7759. * @param currentTarget defines he current object in the bubbling phase
  7760. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7761. */
  7762. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7763. var _this = this;
  7764. if (mask === void 0) { mask = -1; }
  7765. // create an empty promise
  7766. var p = Promise.resolve(eventData);
  7767. // no observers? return this promise.
  7768. if (!this._observers.length) {
  7769. return p;
  7770. }
  7771. var state = this._eventState;
  7772. state.mask = mask;
  7773. state.target = target;
  7774. state.currentTarget = currentTarget;
  7775. state.skipNextObservers = false;
  7776. // execute one callback after another (not using Promise.all, the order is important)
  7777. this._observers.forEach(function (obs) {
  7778. if (state.skipNextObservers) {
  7779. return;
  7780. }
  7781. if (obs._willBeUnregistered) {
  7782. return;
  7783. }
  7784. if (obs.mask & mask) {
  7785. if (obs.scope) {
  7786. p = p.then(function (lastReturnedValue) {
  7787. state.lastReturnValue = lastReturnedValue;
  7788. return obs.callback.apply(obs.scope, [eventData, state]);
  7789. });
  7790. }
  7791. else {
  7792. p = p.then(function (lastReturnedValue) {
  7793. state.lastReturnValue = lastReturnedValue;
  7794. return obs.callback(eventData, state);
  7795. });
  7796. }
  7797. if (obs.unregisterOnNextCall) {
  7798. _this._deferUnregister(obs);
  7799. }
  7800. }
  7801. });
  7802. // return the eventData
  7803. return p.then(function () { return eventData; });
  7804. };
  7805. /**
  7806. * Notify a specific observer
  7807. * @param observer defines the observer to notify
  7808. * @param eventData defines the data to be sent to each callback
  7809. * @param mask is used to filter observers defaults to -1
  7810. */
  7811. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7812. if (mask === void 0) { mask = -1; }
  7813. var state = this._eventState;
  7814. state.mask = mask;
  7815. state.skipNextObservers = false;
  7816. observer.callback(eventData, state);
  7817. };
  7818. /**
  7819. * Gets a boolean indicating if the observable has at least one observer
  7820. * @returns true is the Observable has at least one Observer registered
  7821. */
  7822. Observable.prototype.hasObservers = function () {
  7823. return this._observers.length > 0;
  7824. };
  7825. /**
  7826. * Clear the list of observers
  7827. */
  7828. Observable.prototype.clear = function () {
  7829. this._observers = new Array();
  7830. this._onObserverAdded = null;
  7831. };
  7832. /**
  7833. * Clone the current observable
  7834. * @returns a new observable
  7835. */
  7836. Observable.prototype.clone = function () {
  7837. var result = new Observable();
  7838. result._observers = this._observers.slice(0);
  7839. return result;
  7840. };
  7841. /**
  7842. * Does this observable handles observer registered with a given mask
  7843. * @param mask defines the mask to be tested
  7844. * @return whether or not one observer registered with the given mask is handeled
  7845. **/
  7846. Observable.prototype.hasSpecificMask = function (mask) {
  7847. if (mask === void 0) { mask = -1; }
  7848. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7849. var obs = _a[_i];
  7850. if (obs.mask & mask || obs.mask === mask) {
  7851. return true;
  7852. }
  7853. }
  7854. return false;
  7855. };
  7856. return Observable;
  7857. }());
  7858. BABYLON.Observable = Observable;
  7859. })(BABYLON || (BABYLON = {}));
  7860. //# sourceMappingURL=babylon.observable.js.map
  7861. "use strict";
  7862. var BABYLON;
  7863. (function (BABYLON) {
  7864. var SmartArray = /** @class */ (function () {
  7865. function SmartArray(capacity) {
  7866. this.length = 0;
  7867. this.data = new Array(capacity);
  7868. this._id = SmartArray._GlobalId++;
  7869. }
  7870. SmartArray.prototype.push = function (value) {
  7871. this.data[this.length++] = value;
  7872. if (this.length > this.data.length) {
  7873. this.data.length *= 2;
  7874. }
  7875. };
  7876. SmartArray.prototype.forEach = function (func) {
  7877. for (var index = 0; index < this.length; index++) {
  7878. func(this.data[index]);
  7879. }
  7880. };
  7881. SmartArray.prototype.sort = function (compareFn) {
  7882. this.data.sort(compareFn);
  7883. };
  7884. SmartArray.prototype.reset = function () {
  7885. this.length = 0;
  7886. };
  7887. SmartArray.prototype.dispose = function () {
  7888. this.reset();
  7889. if (this.data) {
  7890. this.data.length = 0;
  7891. this.data = [];
  7892. }
  7893. };
  7894. SmartArray.prototype.concat = function (array) {
  7895. if (array.length === 0) {
  7896. return;
  7897. }
  7898. if (this.length + array.length > this.data.length) {
  7899. this.data.length = (this.length + array.length) * 2;
  7900. }
  7901. for (var index = 0; index < array.length; index++) {
  7902. this.data[this.length++] = (array.data || array)[index];
  7903. }
  7904. };
  7905. SmartArray.prototype.indexOf = function (value) {
  7906. var position = this.data.indexOf(value);
  7907. if (position >= this.length) {
  7908. return -1;
  7909. }
  7910. return position;
  7911. };
  7912. SmartArray.prototype.contains = function (value) {
  7913. return this.data.indexOf(value) !== -1;
  7914. };
  7915. // Statics
  7916. SmartArray._GlobalId = 0;
  7917. return SmartArray;
  7918. }());
  7919. BABYLON.SmartArray = SmartArray;
  7920. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7921. __extends(SmartArrayNoDuplicate, _super);
  7922. function SmartArrayNoDuplicate() {
  7923. var _this = _super !== null && _super.apply(this, arguments) || this;
  7924. _this._duplicateId = 0;
  7925. return _this;
  7926. }
  7927. SmartArrayNoDuplicate.prototype.push = function (value) {
  7928. _super.prototype.push.call(this, value);
  7929. if (!value.__smartArrayFlags) {
  7930. value.__smartArrayFlags = {};
  7931. }
  7932. value.__smartArrayFlags[this._id] = this._duplicateId;
  7933. };
  7934. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7935. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7936. return false;
  7937. }
  7938. this.push(value);
  7939. return true;
  7940. };
  7941. SmartArrayNoDuplicate.prototype.reset = function () {
  7942. _super.prototype.reset.call(this);
  7943. this._duplicateId++;
  7944. };
  7945. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7946. if (array.length === 0) {
  7947. return;
  7948. }
  7949. if (this.length + array.length > this.data.length) {
  7950. this.data.length = (this.length + array.length) * 2;
  7951. }
  7952. for (var index = 0; index < array.length; index++) {
  7953. var item = (array.data || array)[index];
  7954. this.pushNoDuplicate(item);
  7955. }
  7956. };
  7957. return SmartArrayNoDuplicate;
  7958. }(SmartArray));
  7959. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7960. })(BABYLON || (BABYLON = {}));
  7961. //# sourceMappingURL=babylon.smartArray.js.map
  7962. "use strict";
  7963. var BABYLON;
  7964. (function (BABYLON) {
  7965. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7966. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7967. var LoadFileError = /** @class */ (function (_super) {
  7968. __extends(LoadFileError, _super);
  7969. function LoadFileError(message, request) {
  7970. var _this = _super.call(this, message) || this;
  7971. _this.request = request;
  7972. _this.name = "LoadFileError";
  7973. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7974. return _this;
  7975. }
  7976. // Polyfill for Object.setPrototypeOf if necessary.
  7977. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7978. return LoadFileError;
  7979. }(Error));
  7980. BABYLON.LoadFileError = LoadFileError;
  7981. var RetryStrategy = /** @class */ (function () {
  7982. function RetryStrategy() {
  7983. }
  7984. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7985. if (maxRetries === void 0) { maxRetries = 3; }
  7986. if (baseInterval === void 0) { baseInterval = 500; }
  7987. return function (url, request, retryIndex) {
  7988. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7989. return -1;
  7990. }
  7991. return Math.pow(2, retryIndex) * baseInterval;
  7992. };
  7993. };
  7994. return RetryStrategy;
  7995. }());
  7996. BABYLON.RetryStrategy = RetryStrategy;
  7997. // Screenshots
  7998. var screenshotCanvas;
  7999. var cloneValue = function (source, destinationObject) {
  8000. if (!source)
  8001. return null;
  8002. if (source instanceof BABYLON.Mesh) {
  8003. return null;
  8004. }
  8005. if (source instanceof BABYLON.SubMesh) {
  8006. return source.clone(destinationObject);
  8007. }
  8008. else if (source.clone) {
  8009. return source.clone();
  8010. }
  8011. return null;
  8012. };
  8013. var Tools = /** @class */ (function () {
  8014. function Tools() {
  8015. }
  8016. /**
  8017. * Interpolates between a and b via alpha
  8018. * @param a The lower value (returned when alpha = 0)
  8019. * @param b The upper value (returned when alpha = 1)
  8020. * @param alpha The interpolation-factor
  8021. * @return The mixed value
  8022. */
  8023. Tools.Mix = function (a, b, alpha) {
  8024. return a * (1 - alpha) + b * alpha;
  8025. };
  8026. Tools.Instantiate = function (className) {
  8027. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8028. return Tools.RegisteredExternalClasses[className];
  8029. }
  8030. var arr = className.split(".");
  8031. var fn = (window || this);
  8032. for (var i = 0, len = arr.length; i < len; i++) {
  8033. fn = fn[arr[i]];
  8034. }
  8035. if (typeof fn !== "function") {
  8036. return null;
  8037. }
  8038. return fn;
  8039. };
  8040. /**
  8041. * Provides a slice function that will work even on IE
  8042. * @param data defines the array to slice
  8043. * @param start defines the start of the data (optional)
  8044. * @param end defines the end of the data (optional)
  8045. * @returns the new sliced array
  8046. */
  8047. Tools.Slice = function (data, start, end) {
  8048. if (data.slice) {
  8049. return data.slice(start, end);
  8050. }
  8051. return Array.prototype.slice.call(data, start, end);
  8052. };
  8053. Tools.SetImmediate = function (action) {
  8054. if (window.setImmediate) {
  8055. window.setImmediate(action);
  8056. }
  8057. else {
  8058. setTimeout(action, 1);
  8059. }
  8060. };
  8061. Tools.IsExponentOfTwo = function (value) {
  8062. var count = 1;
  8063. do {
  8064. count *= 2;
  8065. } while (count < value);
  8066. return count === value;
  8067. };
  8068. /**
  8069. * Find the next highest power of two.
  8070. * @param x Number to start search from.
  8071. * @return Next highest power of two.
  8072. */
  8073. Tools.CeilingPOT = function (x) {
  8074. x--;
  8075. x |= x >> 1;
  8076. x |= x >> 2;
  8077. x |= x >> 4;
  8078. x |= x >> 8;
  8079. x |= x >> 16;
  8080. x++;
  8081. return x;
  8082. };
  8083. /**
  8084. * Find the next lowest power of two.
  8085. * @param x Number to start search from.
  8086. * @return Next lowest power of two.
  8087. */
  8088. Tools.FloorPOT = function (x) {
  8089. x = x | (x >> 1);
  8090. x = x | (x >> 2);
  8091. x = x | (x >> 4);
  8092. x = x | (x >> 8);
  8093. x = x | (x >> 16);
  8094. return x - (x >> 1);
  8095. };
  8096. /**
  8097. * Find the nearest power of two.
  8098. * @param x Number to start search from.
  8099. * @return Next nearest power of two.
  8100. */
  8101. Tools.NearestPOT = function (x) {
  8102. var c = Tools.CeilingPOT(x);
  8103. var f = Tools.FloorPOT(x);
  8104. return (c - x) > (x - f) ? f : c;
  8105. };
  8106. Tools.GetExponentOfTwo = function (value, max, mode) {
  8107. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8108. var pot;
  8109. switch (mode) {
  8110. case BABYLON.Engine.SCALEMODE_FLOOR:
  8111. pot = Tools.FloorPOT(value);
  8112. break;
  8113. case BABYLON.Engine.SCALEMODE_NEAREST:
  8114. pot = Tools.NearestPOT(value);
  8115. break;
  8116. case BABYLON.Engine.SCALEMODE_CEILING:
  8117. default:
  8118. pot = Tools.CeilingPOT(value);
  8119. break;
  8120. }
  8121. return Math.min(pot, max);
  8122. };
  8123. Tools.GetFilename = function (path) {
  8124. var index = path.lastIndexOf("/");
  8125. if (index < 0)
  8126. return path;
  8127. return path.substring(index + 1);
  8128. };
  8129. /**
  8130. * Extracts the "folder" part of a path (everything before the filename).
  8131. * @param uri The URI to extract the info from
  8132. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8133. * @returns The "folder" part of the path
  8134. */
  8135. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8136. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8137. var index = uri.lastIndexOf("/");
  8138. if (index < 0) {
  8139. if (returnUnchangedIfNoSlash) {
  8140. return uri;
  8141. }
  8142. return "";
  8143. }
  8144. return uri.substring(0, index + 1);
  8145. };
  8146. Tools.GetDOMTextContent = function (element) {
  8147. var result = "";
  8148. var child = element.firstChild;
  8149. while (child) {
  8150. if (child.nodeType === 3) {
  8151. result += child.textContent;
  8152. }
  8153. child = child.nextSibling;
  8154. }
  8155. return result;
  8156. };
  8157. Tools.ToDegrees = function (angle) {
  8158. return angle * 180 / Math.PI;
  8159. };
  8160. Tools.ToRadians = function (angle) {
  8161. return angle * Math.PI / 180;
  8162. };
  8163. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8164. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8165. var output = "";
  8166. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8167. var i = 0;
  8168. var bytes = new Uint8Array(buffer);
  8169. while (i < bytes.length) {
  8170. chr1 = bytes[i++];
  8171. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8172. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8173. enc1 = chr1 >> 2;
  8174. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8175. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8176. enc4 = chr3 & 63;
  8177. if (isNaN(chr2)) {
  8178. enc3 = enc4 = 64;
  8179. }
  8180. else if (isNaN(chr3)) {
  8181. enc4 = 64;
  8182. }
  8183. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8184. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8185. }
  8186. return "data:image/png;base64," + output;
  8187. };
  8188. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8189. if (bias === void 0) { bias = null; }
  8190. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8191. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8192. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8193. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8194. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8195. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8196. }
  8197. if (bias) {
  8198. minimum.x -= minimum.x * bias.x + bias.y;
  8199. minimum.y -= minimum.y * bias.x + bias.y;
  8200. minimum.z -= minimum.z * bias.x + bias.y;
  8201. maximum.x += maximum.x * bias.x + bias.y;
  8202. maximum.y += maximum.y * bias.x + bias.y;
  8203. maximum.z += maximum.z * bias.x + bias.y;
  8204. }
  8205. return {
  8206. minimum: minimum,
  8207. maximum: maximum
  8208. };
  8209. };
  8210. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8211. if (bias === void 0) { bias = null; }
  8212. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8213. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8214. if (!stride) {
  8215. stride = 3;
  8216. }
  8217. for (var index = start; index < start + count; index++) {
  8218. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8219. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8220. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8221. }
  8222. if (bias) {
  8223. minimum.x -= minimum.x * bias.x + bias.y;
  8224. minimum.y -= minimum.y * bias.x + bias.y;
  8225. minimum.z -= minimum.z * bias.x + bias.y;
  8226. maximum.x += maximum.x * bias.x + bias.y;
  8227. maximum.y += maximum.y * bias.x + bias.y;
  8228. maximum.z += maximum.z * bias.x + bias.y;
  8229. }
  8230. return {
  8231. minimum: minimum,
  8232. maximum: maximum
  8233. };
  8234. };
  8235. Tools.Vector2ArrayFeeder = function (array) {
  8236. return function (index) {
  8237. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8238. var length = isFloatArray ? array.length / 2 : array.length;
  8239. if (index >= length) {
  8240. return null;
  8241. }
  8242. if (isFloatArray) {
  8243. var fa = array;
  8244. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8245. }
  8246. var a = array;
  8247. return a[index];
  8248. };
  8249. };
  8250. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8251. if (bias === void 0) { bias = null; }
  8252. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8253. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8254. var i = 0;
  8255. var cur = feeder(i++);
  8256. while (cur) {
  8257. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8258. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8259. cur = feeder(i++);
  8260. }
  8261. if (bias) {
  8262. minimum.x -= minimum.x * bias.x + bias.y;
  8263. minimum.y -= minimum.y * bias.x + bias.y;
  8264. maximum.x += maximum.x * bias.x + bias.y;
  8265. maximum.y += maximum.y * bias.x + bias.y;
  8266. }
  8267. return {
  8268. minimum: minimum,
  8269. maximum: maximum
  8270. };
  8271. };
  8272. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8273. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8274. return null;
  8275. return Array.isArray(obj) ? obj : [obj];
  8276. };
  8277. // Misc.
  8278. Tools.GetPointerPrefix = function () {
  8279. var eventPrefix = "pointer";
  8280. // Check if pointer events are supported
  8281. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8282. eventPrefix = "mouse";
  8283. }
  8284. return eventPrefix;
  8285. };
  8286. /**
  8287. * @param func - the function to be called
  8288. * @param requester - the object that will request the next frame. Falls back to window.
  8289. */
  8290. Tools.QueueNewFrame = function (func, requester) {
  8291. if (!Tools.IsWindowObjectExist()) {
  8292. return setTimeout(func, 16);
  8293. }
  8294. if (!requester) {
  8295. requester = window;
  8296. }
  8297. if (requester.requestAnimationFrame) {
  8298. return requester.requestAnimationFrame(func);
  8299. }
  8300. else if (requester.msRequestAnimationFrame) {
  8301. return requester.msRequestAnimationFrame(func);
  8302. }
  8303. else if (requester.webkitRequestAnimationFrame) {
  8304. return requester.webkitRequestAnimationFrame(func);
  8305. }
  8306. else if (requester.mozRequestAnimationFrame) {
  8307. return requester.mozRequestAnimationFrame(func);
  8308. }
  8309. else if (requester.oRequestAnimationFrame) {
  8310. return requester.oRequestAnimationFrame(func);
  8311. }
  8312. else {
  8313. return window.setTimeout(func, 16);
  8314. }
  8315. };
  8316. Tools.RequestFullscreen = function (element) {
  8317. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8318. if (!requestFunction)
  8319. return;
  8320. requestFunction.call(element);
  8321. };
  8322. Tools.ExitFullscreen = function () {
  8323. if (document.exitFullscreen) {
  8324. document.exitFullscreen();
  8325. }
  8326. else if (document.mozCancelFullScreen) {
  8327. document.mozCancelFullScreen();
  8328. }
  8329. else if (document.webkitCancelFullScreen) {
  8330. document.webkitCancelFullScreen();
  8331. }
  8332. else if (document.msCancelFullScreen) {
  8333. document.msCancelFullScreen();
  8334. }
  8335. };
  8336. Tools.SetCorsBehavior = function (url, element) {
  8337. if (url && url.indexOf("data:") === 0) {
  8338. return;
  8339. }
  8340. if (Tools.CorsBehavior) {
  8341. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8342. element.crossOrigin = Tools.CorsBehavior;
  8343. }
  8344. else {
  8345. var result = Tools.CorsBehavior(url);
  8346. if (result) {
  8347. element.crossOrigin = result;
  8348. }
  8349. }
  8350. }
  8351. };
  8352. // External files
  8353. Tools.CleanUrl = function (url) {
  8354. url = url.replace(/#/mg, "%23");
  8355. return url;
  8356. };
  8357. Tools.LoadImage = function (url, onLoad, onError, database) {
  8358. if (url instanceof ArrayBuffer) {
  8359. url = Tools.EncodeArrayBufferTobase64(url);
  8360. }
  8361. url = Tools.CleanUrl(url);
  8362. url = Tools.PreprocessUrl(url);
  8363. var img = new Image();
  8364. Tools.SetCorsBehavior(url, img);
  8365. var loadHandler = function () {
  8366. img.removeEventListener("load", loadHandler);
  8367. img.removeEventListener("error", errorHandler);
  8368. onLoad(img);
  8369. };
  8370. var errorHandler = function (err) {
  8371. img.removeEventListener("load", loadHandler);
  8372. img.removeEventListener("error", errorHandler);
  8373. Tools.Error("Error while trying to load image: " + url);
  8374. if (onError) {
  8375. onError("Error while trying to load image: " + url, err);
  8376. }
  8377. };
  8378. img.addEventListener("load", loadHandler);
  8379. img.addEventListener("error", errorHandler);
  8380. var noIndexedDB = function () {
  8381. img.src = url;
  8382. };
  8383. var loadFromIndexedDB = function () {
  8384. if (database) {
  8385. database.loadImageFromDB(url, img);
  8386. }
  8387. };
  8388. //ANY database to do!
  8389. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8390. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8391. }
  8392. else {
  8393. if (url.indexOf("file:") !== -1) {
  8394. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8395. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8396. try {
  8397. var blobURL;
  8398. try {
  8399. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8400. }
  8401. catch (ex) {
  8402. // Chrome doesn't support oneTimeOnly parameter
  8403. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8404. }
  8405. img.src = blobURL;
  8406. }
  8407. catch (e) {
  8408. img.src = "";
  8409. }
  8410. return img;
  8411. }
  8412. }
  8413. noIndexedDB();
  8414. }
  8415. return img;
  8416. };
  8417. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8418. url = Tools.CleanUrl(url);
  8419. url = Tools.PreprocessUrl(url);
  8420. // If file and file input are set
  8421. if (url.indexOf("file:") !== -1) {
  8422. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8423. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8424. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8425. }
  8426. }
  8427. var loadUrl = Tools.BaseUrl + url;
  8428. var aborted = false;
  8429. var fileRequest = {
  8430. onCompleteObservable: new BABYLON.Observable(),
  8431. abort: function () { return aborted = true; },
  8432. };
  8433. var requestFile = function () {
  8434. var request = new XMLHttpRequest();
  8435. var retryHandle = null;
  8436. fileRequest.abort = function () {
  8437. aborted = true;
  8438. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8439. request.abort();
  8440. }
  8441. if (retryHandle !== null) {
  8442. clearTimeout(retryHandle);
  8443. retryHandle = null;
  8444. }
  8445. };
  8446. var retryLoop = function (retryIndex) {
  8447. request.open('GET', loadUrl, true);
  8448. if (useArrayBuffer) {
  8449. request.responseType = "arraybuffer";
  8450. }
  8451. if (onProgress) {
  8452. request.addEventListener("progress", onProgress);
  8453. }
  8454. var onLoadEnd = function () {
  8455. request.removeEventListener("loadend", onLoadEnd);
  8456. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8457. fileRequest.onCompleteObservable.clear();
  8458. };
  8459. request.addEventListener("loadend", onLoadEnd);
  8460. var onReadyStateChange = function () {
  8461. if (aborted) {
  8462. return;
  8463. }
  8464. // In case of undefined state in some browsers.
  8465. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8466. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8467. request.removeEventListener("readystatechange", onReadyStateChange);
  8468. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8469. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8470. return;
  8471. }
  8472. var retryStrategy = Tools.DefaultRetryStrategy;
  8473. if (retryStrategy) {
  8474. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8475. if (waitTime !== -1) {
  8476. // Prevent the request from completing for retry.
  8477. request.removeEventListener("loadend", onLoadEnd);
  8478. request = new XMLHttpRequest();
  8479. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8480. return;
  8481. }
  8482. }
  8483. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8484. if (onError) {
  8485. onError(request, e);
  8486. }
  8487. else {
  8488. throw e;
  8489. }
  8490. }
  8491. };
  8492. request.addEventListener("readystatechange", onReadyStateChange);
  8493. request.send();
  8494. };
  8495. retryLoop(0);
  8496. };
  8497. // Caching all files
  8498. if (database && database.enableSceneOffline) {
  8499. var noIndexedDB_1 = function () {
  8500. if (!aborted) {
  8501. requestFile();
  8502. }
  8503. };
  8504. var loadFromIndexedDB = function () {
  8505. // TODO: database needs to support aborting and should return a IFileRequest
  8506. if (aborted) {
  8507. return;
  8508. }
  8509. if (database) {
  8510. database.loadFileFromDB(url, function (data) {
  8511. if (!aborted) {
  8512. onSuccess(data);
  8513. }
  8514. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8515. }, onProgress ? function (event) {
  8516. if (!aborted) {
  8517. onProgress(event);
  8518. }
  8519. } : undefined, noIndexedDB_1, useArrayBuffer);
  8520. }
  8521. };
  8522. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8523. }
  8524. else {
  8525. requestFile();
  8526. }
  8527. return fileRequest;
  8528. };
  8529. /**
  8530. * Load a script (identified by an url). When the url returns, the
  8531. * content of this file is added into a new script element, attached to the DOM (body element)
  8532. */
  8533. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8534. var head = document.getElementsByTagName('head')[0];
  8535. var script = document.createElement('script');
  8536. script.type = 'text/javascript';
  8537. script.src = scriptUrl;
  8538. script.onload = function () {
  8539. if (onSuccess) {
  8540. onSuccess();
  8541. }
  8542. };
  8543. script.onerror = function (e) {
  8544. if (onError) {
  8545. onError("Unable to load script", e);
  8546. }
  8547. };
  8548. head.appendChild(script);
  8549. };
  8550. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8551. var reader = new FileReader();
  8552. var request = {
  8553. onCompleteObservable: new BABYLON.Observable(),
  8554. abort: function () { return reader.abort(); },
  8555. };
  8556. reader.onloadend = function (e) {
  8557. request.onCompleteObservable.notifyObservers(request);
  8558. };
  8559. reader.onload = function (e) {
  8560. //target doesn't have result from ts 1.3
  8561. callback(e.target['result']);
  8562. };
  8563. reader.onprogress = progressCallback;
  8564. reader.readAsDataURL(fileToLoad);
  8565. return request;
  8566. };
  8567. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8568. var reader = new FileReader();
  8569. var request = {
  8570. onCompleteObservable: new BABYLON.Observable(),
  8571. abort: function () { return reader.abort(); },
  8572. };
  8573. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8574. reader.onerror = function (e) {
  8575. Tools.Log("Error while reading file: " + fileToLoad.name);
  8576. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8577. };
  8578. reader.onload = function (e) {
  8579. //target doesn't have result from ts 1.3
  8580. callback(e.target['result']);
  8581. };
  8582. if (progressCallBack) {
  8583. reader.onprogress = progressCallBack;
  8584. }
  8585. if (!useArrayBuffer) {
  8586. // Asynchronous read
  8587. reader.readAsText(fileToLoad);
  8588. }
  8589. else {
  8590. reader.readAsArrayBuffer(fileToLoad);
  8591. }
  8592. return request;
  8593. };
  8594. //returns a downloadable url to a file content.
  8595. Tools.FileAsURL = function (content) {
  8596. var fileBlob = new Blob([content]);
  8597. var url = window.URL || window.webkitURL;
  8598. var link = url.createObjectURL(fileBlob);
  8599. return link;
  8600. };
  8601. // Misc.
  8602. Tools.Format = function (value, decimals) {
  8603. if (decimals === void 0) { decimals = 2; }
  8604. return value.toFixed(decimals);
  8605. };
  8606. Tools.CheckExtends = function (v, min, max) {
  8607. if (v.x < min.x)
  8608. min.x = v.x;
  8609. if (v.y < min.y)
  8610. min.y = v.y;
  8611. if (v.z < min.z)
  8612. min.z = v.z;
  8613. if (v.x > max.x)
  8614. max.x = v.x;
  8615. if (v.y > max.y)
  8616. max.y = v.y;
  8617. if (v.z > max.z)
  8618. max.z = v.z;
  8619. };
  8620. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8621. for (var prop in source) {
  8622. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8623. continue;
  8624. }
  8625. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8626. continue;
  8627. }
  8628. var sourceValue = source[prop];
  8629. var typeOfSourceValue = typeof sourceValue;
  8630. if (typeOfSourceValue === "function") {
  8631. continue;
  8632. }
  8633. try {
  8634. if (typeOfSourceValue === "object") {
  8635. if (sourceValue instanceof Array) {
  8636. destination[prop] = [];
  8637. if (sourceValue.length > 0) {
  8638. if (typeof sourceValue[0] == "object") {
  8639. for (var index = 0; index < sourceValue.length; index++) {
  8640. var clonedValue = cloneValue(sourceValue[index], destination);
  8641. if (destination[prop].indexOf(clonedValue) === -1) {
  8642. destination[prop].push(clonedValue);
  8643. }
  8644. }
  8645. }
  8646. else {
  8647. destination[prop] = sourceValue.slice(0);
  8648. }
  8649. }
  8650. }
  8651. else {
  8652. destination[prop] = cloneValue(sourceValue, destination);
  8653. }
  8654. }
  8655. else {
  8656. destination[prop] = sourceValue;
  8657. }
  8658. }
  8659. catch (e) {
  8660. // Just ignore error (it could be because of a read-only property)
  8661. }
  8662. }
  8663. };
  8664. Tools.IsEmpty = function (obj) {
  8665. for (var i in obj) {
  8666. if (obj.hasOwnProperty(i)) {
  8667. return false;
  8668. }
  8669. }
  8670. return true;
  8671. };
  8672. Tools.RegisterTopRootEvents = function (events) {
  8673. for (var index = 0; index < events.length; index++) {
  8674. var event = events[index];
  8675. window.addEventListener(event.name, event.handler, false);
  8676. try {
  8677. if (window.parent) {
  8678. window.parent.addEventListener(event.name, event.handler, false);
  8679. }
  8680. }
  8681. catch (e) {
  8682. // Silently fails...
  8683. }
  8684. }
  8685. };
  8686. Tools.UnregisterTopRootEvents = function (events) {
  8687. for (var index = 0; index < events.length; index++) {
  8688. var event = events[index];
  8689. window.removeEventListener(event.name, event.handler);
  8690. try {
  8691. if (window.parent) {
  8692. window.parent.removeEventListener(event.name, event.handler);
  8693. }
  8694. }
  8695. catch (e) {
  8696. // Silently fails...
  8697. }
  8698. }
  8699. };
  8700. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8701. if (mimeType === void 0) { mimeType = "image/png"; }
  8702. // Read the contents of the framebuffer
  8703. var numberOfChannelsByLine = width * 4;
  8704. var halfHeight = height / 2;
  8705. //Reading datas from WebGL
  8706. var data = engine.readPixels(0, 0, width, height);
  8707. //To flip image on Y axis.
  8708. for (var i = 0; i < halfHeight; i++) {
  8709. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8710. var currentCell = j + i * numberOfChannelsByLine;
  8711. var targetLine = height - i - 1;
  8712. var targetCell = j + targetLine * numberOfChannelsByLine;
  8713. var temp = data[currentCell];
  8714. data[currentCell] = data[targetCell];
  8715. data[targetCell] = temp;
  8716. }
  8717. }
  8718. // Create a 2D canvas to store the result
  8719. if (!screenshotCanvas) {
  8720. screenshotCanvas = document.createElement('canvas');
  8721. }
  8722. screenshotCanvas.width = width;
  8723. screenshotCanvas.height = height;
  8724. var context = screenshotCanvas.getContext('2d');
  8725. if (context) {
  8726. // Copy the pixels to a 2D canvas
  8727. var imageData = context.createImageData(width, height);
  8728. var castData = (imageData.data);
  8729. castData.set(data);
  8730. context.putImageData(imageData, 0, 0);
  8731. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8732. }
  8733. };
  8734. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8735. if (mimeType === void 0) { mimeType = "image/png"; }
  8736. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8737. if (successCallback) {
  8738. successCallback(base64Image);
  8739. }
  8740. else {
  8741. // We need HTMLCanvasElement.toBlob for HD screenshots
  8742. if (!screenshotCanvas.toBlob) {
  8743. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8744. screenshotCanvas.toBlob = function (callback, type, quality) {
  8745. var _this = this;
  8746. setTimeout(function () {
  8747. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8748. for (var i = 0; i < len; i++) {
  8749. arr[i] = binStr.charCodeAt(i);
  8750. }
  8751. callback(new Blob([arr], { type: type || 'image/png' }));
  8752. });
  8753. };
  8754. }
  8755. screenshotCanvas.toBlob(function (blob) {
  8756. var url = URL.createObjectURL(blob);
  8757. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8758. if (("download" in document.createElement("a"))) {
  8759. var a = window.document.createElement("a");
  8760. a.href = url;
  8761. if (fileName) {
  8762. a.setAttribute("download", fileName);
  8763. }
  8764. else {
  8765. var date = new Date();
  8766. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8767. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8768. }
  8769. window.document.body.appendChild(a);
  8770. a.addEventListener("click", function () {
  8771. if (a.parentElement) {
  8772. a.parentElement.removeChild(a);
  8773. }
  8774. });
  8775. a.click();
  8776. }
  8777. else {
  8778. var newWindow = window.open("");
  8779. if (!newWindow)
  8780. return;
  8781. var img = newWindow.document.createElement("img");
  8782. img.onload = function () {
  8783. // no longer need to read the blob so it's revoked
  8784. URL.revokeObjectURL(url);
  8785. };
  8786. img.src = url;
  8787. newWindow.document.body.appendChild(img);
  8788. }
  8789. });
  8790. }
  8791. };
  8792. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8793. if (mimeType === void 0) { mimeType = "image/png"; }
  8794. var width;
  8795. var height;
  8796. // If a precision value is specified
  8797. if (size.precision) {
  8798. width = Math.round(engine.getRenderWidth() * size.precision);
  8799. height = Math.round(width / engine.getAspectRatio(camera));
  8800. }
  8801. else if (size.width && size.height) {
  8802. width = size.width;
  8803. height = size.height;
  8804. }
  8805. else if (size.width && !size.height) {
  8806. width = size.width;
  8807. height = Math.round(width / engine.getAspectRatio(camera));
  8808. }
  8809. else if (size.height && !size.width) {
  8810. height = size.height;
  8811. width = Math.round(height * engine.getAspectRatio(camera));
  8812. }
  8813. else if (!isNaN(size)) {
  8814. height = size;
  8815. width = size;
  8816. }
  8817. else {
  8818. Tools.Error("Invalid 'size' parameter !");
  8819. return;
  8820. }
  8821. if (!screenshotCanvas) {
  8822. screenshotCanvas = document.createElement('canvas');
  8823. }
  8824. screenshotCanvas.width = width;
  8825. screenshotCanvas.height = height;
  8826. var renderContext = screenshotCanvas.getContext("2d");
  8827. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8828. var newWidth = width;
  8829. var newHeight = newWidth / ratio;
  8830. if (newHeight > height) {
  8831. newHeight = height;
  8832. newWidth = newHeight * ratio;
  8833. }
  8834. var offsetX = Math.max(0, width - newWidth) / 2;
  8835. var offsetY = Math.max(0, height - newHeight) / 2;
  8836. var renderingCanvas = engine.getRenderingCanvas();
  8837. if (renderContext && renderingCanvas) {
  8838. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8839. }
  8840. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8841. };
  8842. /**
  8843. * Generates an image screenshot from the specified camera.
  8844. *
  8845. * @param engine The engine to use for rendering
  8846. * @param camera The camera to use for rendering
  8847. * @param size This parameter can be set to a single number or to an object with the
  8848. * following (optional) properties: precision, width, height. If a single number is passed,
  8849. * it will be used for both width and height. If an object is passed, the screenshot size
  8850. * will be derived from the parameters. The precision property is a multiplier allowing
  8851. * rendering at a higher or lower resolution.
  8852. * @param successCallback The callback receives a single parameter which contains the
  8853. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8854. * src parameter of an <img> to display it.
  8855. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8856. * Check your browser for supported MIME types.
  8857. * @param samples Texture samples (default: 1)
  8858. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8859. * @param fileName A name for for the downloaded file.
  8860. * @constructor
  8861. */
  8862. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8863. if (mimeType === void 0) { mimeType = "image/png"; }
  8864. if (samples === void 0) { samples = 1; }
  8865. if (antialiasing === void 0) { antialiasing = false; }
  8866. var width;
  8867. var height;
  8868. //If a precision value is specified
  8869. if (size.precision) {
  8870. width = Math.round(engine.getRenderWidth() * size.precision);
  8871. height = Math.round(width / engine.getAspectRatio(camera));
  8872. size = { width: width, height: height };
  8873. }
  8874. else if (size.width && size.height) {
  8875. width = size.width;
  8876. height = size.height;
  8877. }
  8878. else if (size.width && !size.height) {
  8879. width = size.width;
  8880. height = Math.round(width / engine.getAspectRatio(camera));
  8881. size = { width: width, height: height };
  8882. }
  8883. else if (size.height && !size.width) {
  8884. height = size.height;
  8885. width = Math.round(height * engine.getAspectRatio(camera));
  8886. size = { width: width, height: height };
  8887. }
  8888. else if (!isNaN(size)) {
  8889. height = size;
  8890. width = size;
  8891. }
  8892. else {
  8893. Tools.Error("Invalid 'size' parameter !");
  8894. return;
  8895. }
  8896. var scene = camera.getScene();
  8897. var previousCamera = null;
  8898. if (scene.activeCamera !== camera) {
  8899. previousCamera = scene.activeCamera;
  8900. scene.activeCamera = camera;
  8901. }
  8902. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8903. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8904. texture.renderList = null;
  8905. texture.samples = samples;
  8906. if (antialiasing) {
  8907. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8908. }
  8909. texture.onAfterRenderObservable.add(function () {
  8910. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8911. });
  8912. scene.incrementRenderId();
  8913. scene.resetCachedMaterial();
  8914. texture.render(true);
  8915. texture.dispose();
  8916. if (previousCamera) {
  8917. scene.activeCamera = previousCamera;
  8918. }
  8919. camera.getProjectionMatrix(true); // Force cache refresh;
  8920. };
  8921. // XHR response validator for local file scenario
  8922. Tools.ValidateXHRData = function (xhr, dataType) {
  8923. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8924. if (dataType === void 0) { dataType = 7; }
  8925. try {
  8926. if (dataType & 1) {
  8927. if (xhr.responseText && xhr.responseText.length > 0) {
  8928. return true;
  8929. }
  8930. else if (dataType === 1) {
  8931. return false;
  8932. }
  8933. }
  8934. if (dataType & 2) {
  8935. // Check header width and height since there is no "TGA" magic number
  8936. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8937. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8938. return true;
  8939. }
  8940. else if (dataType === 2) {
  8941. return false;
  8942. }
  8943. }
  8944. if (dataType & 4) {
  8945. // Check for the "DDS" magic number
  8946. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8947. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8948. return true;
  8949. }
  8950. else {
  8951. return false;
  8952. }
  8953. }
  8954. }
  8955. catch (e) {
  8956. // Global protection
  8957. }
  8958. return false;
  8959. };
  8960. /**
  8961. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8962. * Be aware Math.random() could cause collisions, but:
  8963. * "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"
  8964. */
  8965. Tools.RandomId = function () {
  8966. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8967. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8968. return v.toString(16);
  8969. });
  8970. };
  8971. /**
  8972. * Test if the given uri is a base64 string.
  8973. * @param uri The uri to test
  8974. * @return True if the uri is a base64 string or false otherwise.
  8975. */
  8976. Tools.IsBase64 = function (uri) {
  8977. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8978. };
  8979. /**
  8980. * Decode the given base64 uri.
  8981. * @param uri The uri to decode
  8982. * @return The decoded base64 data.
  8983. */
  8984. Tools.DecodeBase64 = function (uri) {
  8985. var decodedString = atob(uri.split(",")[1]);
  8986. var bufferLength = decodedString.length;
  8987. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8988. for (var i = 0; i < bufferLength; i++) {
  8989. bufferView[i] = decodedString.charCodeAt(i);
  8990. }
  8991. return bufferView.buffer;
  8992. };
  8993. Object.defineProperty(Tools, "NoneLogLevel", {
  8994. get: function () {
  8995. return Tools._NoneLogLevel;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. Object.defineProperty(Tools, "MessageLogLevel", {
  9001. get: function () {
  9002. return Tools._MessageLogLevel;
  9003. },
  9004. enumerable: true,
  9005. configurable: true
  9006. });
  9007. Object.defineProperty(Tools, "WarningLogLevel", {
  9008. get: function () {
  9009. return Tools._WarningLogLevel;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. Object.defineProperty(Tools, "ErrorLogLevel", {
  9015. get: function () {
  9016. return Tools._ErrorLogLevel;
  9017. },
  9018. enumerable: true,
  9019. configurable: true
  9020. });
  9021. Object.defineProperty(Tools, "AllLogLevel", {
  9022. get: function () {
  9023. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9024. },
  9025. enumerable: true,
  9026. configurable: true
  9027. });
  9028. Tools._AddLogEntry = function (entry) {
  9029. Tools._LogCache = entry + Tools._LogCache;
  9030. if (Tools.OnNewCacheEntry) {
  9031. Tools.OnNewCacheEntry(entry);
  9032. }
  9033. };
  9034. Tools._FormatMessage = function (message) {
  9035. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9036. var date = new Date();
  9037. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9038. };
  9039. Tools._LogDisabled = function (message) {
  9040. // nothing to do
  9041. };
  9042. Tools._LogEnabled = function (message) {
  9043. var formattedMessage = Tools._FormatMessage(message);
  9044. console.log("BJS - " + formattedMessage);
  9045. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9046. Tools._AddLogEntry(entry);
  9047. };
  9048. Tools._WarnDisabled = function (message) {
  9049. // nothing to do
  9050. };
  9051. Tools._WarnEnabled = function (message) {
  9052. var formattedMessage = Tools._FormatMessage(message);
  9053. console.warn("BJS - " + formattedMessage);
  9054. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9055. Tools._AddLogEntry(entry);
  9056. };
  9057. Tools._ErrorDisabled = function (message) {
  9058. // nothing to do
  9059. };
  9060. Tools._ErrorEnabled = function (message) {
  9061. Tools.errorsCount++;
  9062. var formattedMessage = Tools._FormatMessage(message);
  9063. console.error("BJS - " + formattedMessage);
  9064. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9065. Tools._AddLogEntry(entry);
  9066. };
  9067. Object.defineProperty(Tools, "LogCache", {
  9068. get: function () {
  9069. return Tools._LogCache;
  9070. },
  9071. enumerable: true,
  9072. configurable: true
  9073. });
  9074. Tools.ClearLogCache = function () {
  9075. Tools._LogCache = "";
  9076. Tools.errorsCount = 0;
  9077. };
  9078. Object.defineProperty(Tools, "LogLevels", {
  9079. set: function (level) {
  9080. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9081. Tools.Log = Tools._LogEnabled;
  9082. }
  9083. else {
  9084. Tools.Log = Tools._LogDisabled;
  9085. }
  9086. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9087. Tools.Warn = Tools._WarnEnabled;
  9088. }
  9089. else {
  9090. Tools.Warn = Tools._WarnDisabled;
  9091. }
  9092. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9093. Tools.Error = Tools._ErrorEnabled;
  9094. }
  9095. else {
  9096. Tools.Error = Tools._ErrorDisabled;
  9097. }
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Tools.IsWindowObjectExist = function () {
  9103. return (typeof window) !== "undefined";
  9104. };
  9105. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9106. get: function () {
  9107. return Tools._PerformanceNoneLogLevel;
  9108. },
  9109. enumerable: true,
  9110. configurable: true
  9111. });
  9112. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9113. get: function () {
  9114. return Tools._PerformanceUserMarkLogLevel;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9120. get: function () {
  9121. return Tools._PerformanceConsoleLogLevel;
  9122. },
  9123. enumerable: true,
  9124. configurable: true
  9125. });
  9126. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9127. set: function (level) {
  9128. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9129. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9130. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9131. return;
  9132. }
  9133. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9134. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9135. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9136. return;
  9137. }
  9138. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9139. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9140. },
  9141. enumerable: true,
  9142. configurable: true
  9143. });
  9144. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9145. };
  9146. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9147. };
  9148. Tools._StartUserMark = function (counterName, condition) {
  9149. if (condition === void 0) { condition = true; }
  9150. if (!Tools._performance) {
  9151. if (!Tools.IsWindowObjectExist()) {
  9152. return;
  9153. }
  9154. Tools._performance = window.performance;
  9155. }
  9156. if (!condition || !Tools._performance.mark) {
  9157. return;
  9158. }
  9159. Tools._performance.mark(counterName + "-Begin");
  9160. };
  9161. Tools._EndUserMark = function (counterName, condition) {
  9162. if (condition === void 0) { condition = true; }
  9163. if (!condition || !Tools._performance.mark) {
  9164. return;
  9165. }
  9166. Tools._performance.mark(counterName + "-End");
  9167. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9168. };
  9169. Tools._StartPerformanceConsole = function (counterName, condition) {
  9170. if (condition === void 0) { condition = true; }
  9171. if (!condition) {
  9172. return;
  9173. }
  9174. Tools._StartUserMark(counterName, condition);
  9175. if (console.time) {
  9176. console.time(counterName);
  9177. }
  9178. };
  9179. Tools._EndPerformanceConsole = function (counterName, condition) {
  9180. if (condition === void 0) { condition = true; }
  9181. if (!condition) {
  9182. return;
  9183. }
  9184. Tools._EndUserMark(counterName, condition);
  9185. if (console.time) {
  9186. console.timeEnd(counterName);
  9187. }
  9188. };
  9189. Object.defineProperty(Tools, "Now", {
  9190. get: function () {
  9191. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9192. return window.performance.now();
  9193. }
  9194. return new Date().getTime();
  9195. },
  9196. enumerable: true,
  9197. configurable: true
  9198. });
  9199. /**
  9200. * This method will return the name of the class used to create the instance of the given object.
  9201. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9202. * @param object the object to get the class name from
  9203. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9204. */
  9205. Tools.GetClassName = function (object, isType) {
  9206. if (isType === void 0) { isType = false; }
  9207. var name = null;
  9208. if (!isType && object.getClassName) {
  9209. name = object.getClassName();
  9210. }
  9211. else {
  9212. if (object instanceof Object) {
  9213. var classObj = isType ? object : Object.getPrototypeOf(object);
  9214. name = classObj.constructor["__bjsclassName__"];
  9215. }
  9216. if (!name) {
  9217. name = typeof object;
  9218. }
  9219. }
  9220. return name;
  9221. };
  9222. Tools.First = function (array, predicate) {
  9223. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9224. var el = array_1[_i];
  9225. if (predicate(el)) {
  9226. return el;
  9227. }
  9228. }
  9229. return null;
  9230. };
  9231. /**
  9232. * This method will return the name of the full name of the class, including its owning module (if any).
  9233. * 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).
  9234. * @param object the object to get the class name from
  9235. * @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.
  9236. */
  9237. Tools.getFullClassName = function (object, isType) {
  9238. if (isType === void 0) { isType = false; }
  9239. var className = null;
  9240. var moduleName = null;
  9241. if (!isType && object.getClassName) {
  9242. className = object.getClassName();
  9243. }
  9244. else {
  9245. if (object instanceof Object) {
  9246. var classObj = isType ? object : Object.getPrototypeOf(object);
  9247. className = classObj.constructor["__bjsclassName__"];
  9248. moduleName = classObj.constructor["__bjsmoduleName__"];
  9249. }
  9250. if (!className) {
  9251. className = typeof object;
  9252. }
  9253. }
  9254. if (!className) {
  9255. return null;
  9256. }
  9257. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9258. };
  9259. /**
  9260. * 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.
  9261. * @param array
  9262. */
  9263. Tools.arrayOrStringFeeder = function (array) {
  9264. return function (index) {
  9265. if (index >= array.length) {
  9266. return null;
  9267. }
  9268. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9269. if (val && val.getHashCode) {
  9270. val = val.getHashCode();
  9271. }
  9272. if (typeof val === "string") {
  9273. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9274. }
  9275. return val;
  9276. };
  9277. };
  9278. /**
  9279. * Compute the hashCode of a stream of number
  9280. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9281. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9282. * @return the hash code computed
  9283. */
  9284. Tools.hashCodeFromStream = function (feeder) {
  9285. // Based from here: http://stackoverflow.com/a/7616484/802124
  9286. var hash = 0;
  9287. var index = 0;
  9288. var chr = feeder(index++);
  9289. while (chr != null) {
  9290. hash = ((hash << 5) - hash) + chr;
  9291. hash |= 0; // Convert to 32bit integer
  9292. chr = feeder(index++);
  9293. }
  9294. return hash;
  9295. };
  9296. /**
  9297. * Returns a promise that resolves after the given amount of time.
  9298. * @param delay Number of milliseconds to delay
  9299. * @returns Promise that resolves after the given amount of time
  9300. */
  9301. Tools.DelayAsync = function (delay) {
  9302. return new Promise(function (resolve) {
  9303. setTimeout(function () {
  9304. resolve();
  9305. }, delay);
  9306. });
  9307. };
  9308. Tools.BaseUrl = "";
  9309. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9310. /**
  9311. * Default behaviour for cors in the application.
  9312. * It can be a string if the expected behavior is identical in the entire app.
  9313. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9314. */
  9315. Tools.CorsBehavior = "anonymous";
  9316. Tools.UseFallbackTexture = true;
  9317. /**
  9318. * Use this object to register external classes like custom textures or material
  9319. * to allow the laoders to instantiate them
  9320. */
  9321. Tools.RegisteredExternalClasses = {};
  9322. // Used in case of a texture loading problem
  9323. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9324. Tools.PreprocessUrl = function (url) {
  9325. return url;
  9326. };
  9327. // Logs
  9328. Tools._NoneLogLevel = 0;
  9329. Tools._MessageLogLevel = 1;
  9330. Tools._WarningLogLevel = 2;
  9331. Tools._ErrorLogLevel = 4;
  9332. Tools._LogCache = "";
  9333. Tools.errorsCount = 0;
  9334. Tools.Log = Tools._LogEnabled;
  9335. Tools.Warn = Tools._WarnEnabled;
  9336. Tools.Error = Tools._ErrorEnabled;
  9337. // Performances
  9338. Tools._PerformanceNoneLogLevel = 0;
  9339. Tools._PerformanceUserMarkLogLevel = 1;
  9340. Tools._PerformanceConsoleLogLevel = 2;
  9341. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9342. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9343. return Tools;
  9344. }());
  9345. BABYLON.Tools = Tools;
  9346. /**
  9347. * This class is used to track a performance counter which is number based.
  9348. * The user has access to many properties which give statistics of different nature
  9349. *
  9350. * The implementer can track two kinds of Performance Counter: time and count
  9351. * 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.
  9352. * 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.
  9353. */
  9354. var PerfCounter = /** @class */ (function () {
  9355. function PerfCounter() {
  9356. this._startMonitoringTime = 0;
  9357. this._min = 0;
  9358. this._max = 0;
  9359. this._average = 0;
  9360. this._lastSecAverage = 0;
  9361. this._current = 0;
  9362. this._totalValueCount = 0;
  9363. this._totalAccumulated = 0;
  9364. this._lastSecAccumulated = 0;
  9365. this._lastSecTime = 0;
  9366. this._lastSecValueCount = 0;
  9367. }
  9368. Object.defineProperty(PerfCounter.prototype, "min", {
  9369. /**
  9370. * Returns the smallest value ever
  9371. */
  9372. get: function () {
  9373. return this._min;
  9374. },
  9375. enumerable: true,
  9376. configurable: true
  9377. });
  9378. Object.defineProperty(PerfCounter.prototype, "max", {
  9379. /**
  9380. * Returns the biggest value ever
  9381. */
  9382. get: function () {
  9383. return this._max;
  9384. },
  9385. enumerable: true,
  9386. configurable: true
  9387. });
  9388. Object.defineProperty(PerfCounter.prototype, "average", {
  9389. /**
  9390. * Returns the average value since the performance counter is running
  9391. */
  9392. get: function () {
  9393. return this._average;
  9394. },
  9395. enumerable: true,
  9396. configurable: true
  9397. });
  9398. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9399. /**
  9400. * Returns the average value of the last second the counter was monitored
  9401. */
  9402. get: function () {
  9403. return this._lastSecAverage;
  9404. },
  9405. enumerable: true,
  9406. configurable: true
  9407. });
  9408. Object.defineProperty(PerfCounter.prototype, "current", {
  9409. /**
  9410. * Returns the current value
  9411. */
  9412. get: function () {
  9413. return this._current;
  9414. },
  9415. enumerable: true,
  9416. configurable: true
  9417. });
  9418. Object.defineProperty(PerfCounter.prototype, "total", {
  9419. get: function () {
  9420. return this._totalAccumulated;
  9421. },
  9422. enumerable: true,
  9423. configurable: true
  9424. });
  9425. Object.defineProperty(PerfCounter.prototype, "count", {
  9426. get: function () {
  9427. return this._totalValueCount;
  9428. },
  9429. enumerable: true,
  9430. configurable: true
  9431. });
  9432. /**
  9433. * Call this method to start monitoring a new frame.
  9434. * 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.
  9435. */
  9436. PerfCounter.prototype.fetchNewFrame = function () {
  9437. this._totalValueCount++;
  9438. this._current = 0;
  9439. this._lastSecValueCount++;
  9440. };
  9441. /**
  9442. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9443. * @param newCount the count value to add to the monitored count
  9444. * @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.
  9445. */
  9446. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9447. if (!PerfCounter.Enabled) {
  9448. return;
  9449. }
  9450. this._current += newCount;
  9451. if (fetchResult) {
  9452. this._fetchResult();
  9453. }
  9454. };
  9455. /**
  9456. * Start monitoring this performance counter
  9457. */
  9458. PerfCounter.prototype.beginMonitoring = function () {
  9459. if (!PerfCounter.Enabled) {
  9460. return;
  9461. }
  9462. this._startMonitoringTime = Tools.Now;
  9463. };
  9464. /**
  9465. * Compute the time lapsed since the previous beginMonitoring() call.
  9466. * @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
  9467. */
  9468. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9469. if (newFrame === void 0) { newFrame = true; }
  9470. if (!PerfCounter.Enabled) {
  9471. return;
  9472. }
  9473. if (newFrame) {
  9474. this.fetchNewFrame();
  9475. }
  9476. var currentTime = Tools.Now;
  9477. this._current = currentTime - this._startMonitoringTime;
  9478. if (newFrame) {
  9479. this._fetchResult();
  9480. }
  9481. };
  9482. PerfCounter.prototype._fetchResult = function () {
  9483. this._totalAccumulated += this._current;
  9484. this._lastSecAccumulated += this._current;
  9485. // Min/Max update
  9486. this._min = Math.min(this._min, this._current);
  9487. this._max = Math.max(this._max, this._current);
  9488. this._average = this._totalAccumulated / this._totalValueCount;
  9489. // Reset last sec?
  9490. var now = Tools.Now;
  9491. if ((now - this._lastSecTime) > 1000) {
  9492. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9493. this._lastSecTime = now;
  9494. this._lastSecAccumulated = 0;
  9495. this._lastSecValueCount = 0;
  9496. }
  9497. };
  9498. PerfCounter.Enabled = true;
  9499. return PerfCounter;
  9500. }());
  9501. BABYLON.PerfCounter = PerfCounter;
  9502. /**
  9503. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9504. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9505. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9506. * @param name The name of the class, case should be preserved
  9507. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9508. */
  9509. function className(name, module) {
  9510. return function (target) {
  9511. target["__bjsclassName__"] = name;
  9512. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9513. };
  9514. }
  9515. BABYLON.className = className;
  9516. /**
  9517. * An implementation of a loop for asynchronous functions.
  9518. */
  9519. var AsyncLoop = /** @class */ (function () {
  9520. /**
  9521. * Constroctor.
  9522. * @param iterations the number of iterations.
  9523. * @param _fn the function to run each iteration
  9524. * @param _successCallback the callback that will be called upon succesful execution
  9525. * @param offset starting offset.
  9526. */
  9527. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9528. if (offset === void 0) { offset = 0; }
  9529. this.iterations = iterations;
  9530. this._fn = _fn;
  9531. this._successCallback = _successCallback;
  9532. this.index = offset - 1;
  9533. this._done = false;
  9534. }
  9535. /**
  9536. * Execute the next iteration. Must be called after the last iteration was finished.
  9537. */
  9538. AsyncLoop.prototype.executeNext = function () {
  9539. if (!this._done) {
  9540. if (this.index + 1 < this.iterations) {
  9541. ++this.index;
  9542. this._fn(this);
  9543. }
  9544. else {
  9545. this.breakLoop();
  9546. }
  9547. }
  9548. };
  9549. /**
  9550. * Break the loop and run the success callback.
  9551. */
  9552. AsyncLoop.prototype.breakLoop = function () {
  9553. this._done = true;
  9554. this._successCallback();
  9555. };
  9556. /**
  9557. * Helper function
  9558. */
  9559. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9560. if (offset === void 0) { offset = 0; }
  9561. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9562. loop.executeNext();
  9563. return loop;
  9564. };
  9565. /**
  9566. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9567. * @param iterations total number of iterations
  9568. * @param syncedIterations number of synchronous iterations in each async iteration.
  9569. * @param fn the function to call each iteration.
  9570. * @param callback a success call back that will be called when iterating stops.
  9571. * @param breakFunction a break condition (optional)
  9572. * @param timeout timeout settings for the setTimeout function. default - 0.
  9573. * @constructor
  9574. */
  9575. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9576. if (timeout === void 0) { timeout = 0; }
  9577. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9578. if (breakFunction && breakFunction())
  9579. loop.breakLoop();
  9580. else {
  9581. setTimeout(function () {
  9582. for (var i = 0; i < syncedIterations; ++i) {
  9583. var iteration = (loop.index * syncedIterations) + i;
  9584. if (iteration >= iterations)
  9585. break;
  9586. fn(iteration);
  9587. if (breakFunction && breakFunction()) {
  9588. loop.breakLoop();
  9589. break;
  9590. }
  9591. }
  9592. loop.executeNext();
  9593. }, timeout);
  9594. }
  9595. }, callback);
  9596. };
  9597. return AsyncLoop;
  9598. }());
  9599. BABYLON.AsyncLoop = AsyncLoop;
  9600. })(BABYLON || (BABYLON = {}));
  9601. //# sourceMappingURL=babylon.tools.js.map
  9602. "use strict";
  9603. var BABYLON;
  9604. (function (BABYLON) {
  9605. var PromiseStates;
  9606. (function (PromiseStates) {
  9607. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9608. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9609. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9610. })(PromiseStates || (PromiseStates = {}));
  9611. var FulFillmentAgregator = /** @class */ (function () {
  9612. function FulFillmentAgregator() {
  9613. this.count = 0;
  9614. this.target = 0;
  9615. this.results = [];
  9616. }
  9617. return FulFillmentAgregator;
  9618. }());
  9619. var InternalPromise = /** @class */ (function () {
  9620. function InternalPromise(resolver) {
  9621. var _this = this;
  9622. this._state = PromiseStates.Pending;
  9623. this._children = new Array();
  9624. this._rejectWasConsumed = false;
  9625. if (!resolver) {
  9626. return;
  9627. }
  9628. try {
  9629. resolver(function (value) {
  9630. _this._resolve(value);
  9631. }, function (reason) {
  9632. _this._reject(reason);
  9633. });
  9634. }
  9635. catch (e) {
  9636. this._reject(e);
  9637. }
  9638. }
  9639. InternalPromise.prototype.catch = function (onRejected) {
  9640. return this.then(undefined, onRejected);
  9641. };
  9642. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9643. var _this = this;
  9644. var newPromise = new InternalPromise();
  9645. newPromise._onFulfilled = onFulfilled;
  9646. newPromise._onRejected = onRejected;
  9647. // Composition
  9648. this._children.push(newPromise);
  9649. if (this._state !== PromiseStates.Pending) {
  9650. BABYLON.Tools.SetImmediate(function () {
  9651. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9652. var returnedValue = newPromise._resolve(_this._result);
  9653. if (returnedValue !== undefined && returnedValue !== null) {
  9654. if (returnedValue._state !== undefined) {
  9655. var returnedPromise = returnedValue;
  9656. newPromise._children.push(returnedPromise);
  9657. newPromise = returnedPromise;
  9658. }
  9659. else {
  9660. newPromise._result = returnedValue;
  9661. }
  9662. }
  9663. }
  9664. else {
  9665. newPromise._reject(_this._reason);
  9666. }
  9667. });
  9668. }
  9669. return newPromise;
  9670. };
  9671. InternalPromise.prototype._moveChildren = function (children) {
  9672. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9673. if (this._state === PromiseStates.Fulfilled) {
  9674. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9675. var child = _b[_i];
  9676. child._resolve(this._result);
  9677. }
  9678. }
  9679. else if (this._state === PromiseStates.Rejected) {
  9680. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9681. var child = _d[_c];
  9682. child._reject(this._reason);
  9683. }
  9684. }
  9685. var _a;
  9686. };
  9687. InternalPromise.prototype._resolve = function (value) {
  9688. try {
  9689. this._state = PromiseStates.Fulfilled;
  9690. var returnedValue = null;
  9691. if (this._onFulfilled) {
  9692. returnedValue = this._onFulfilled(value);
  9693. }
  9694. if (returnedValue !== undefined && returnedValue !== null) {
  9695. if (returnedValue._state !== undefined) {
  9696. // Transmit children
  9697. var returnedPromise = returnedValue;
  9698. returnedPromise._moveChildren(this._children);
  9699. value = returnedPromise._result;
  9700. }
  9701. else {
  9702. value = returnedValue;
  9703. }
  9704. }
  9705. this._result = value;
  9706. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9707. var child = _a[_i];
  9708. child._resolve(value);
  9709. }
  9710. this._children.length = 0;
  9711. delete this._onFulfilled;
  9712. delete this._onRejected;
  9713. }
  9714. catch (e) {
  9715. this._reject(e, true);
  9716. }
  9717. };
  9718. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9719. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9720. this._state = PromiseStates.Rejected;
  9721. this._reason = reason;
  9722. if (this._onRejected && !onLocalThrow) {
  9723. try {
  9724. this._onRejected(reason);
  9725. this._rejectWasConsumed = true;
  9726. }
  9727. catch (e) {
  9728. reason = e;
  9729. }
  9730. }
  9731. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9732. var child = _a[_i];
  9733. if (this._rejectWasConsumed) {
  9734. child._resolve(null);
  9735. }
  9736. else {
  9737. child._reject(reason);
  9738. }
  9739. }
  9740. this._children.length = 0;
  9741. delete this._onFulfilled;
  9742. delete this._onRejected;
  9743. };
  9744. InternalPromise.resolve = function (value) {
  9745. var newPromise = new InternalPromise();
  9746. newPromise._resolve(value);
  9747. return newPromise;
  9748. };
  9749. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9750. promise.then(function (value) {
  9751. agregator.results[index] = value;
  9752. agregator.count++;
  9753. if (agregator.count === agregator.target) {
  9754. agregator.rootPromise._resolve(agregator.results);
  9755. }
  9756. return null;
  9757. }, function (reason) {
  9758. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9759. agregator.rootPromise._reject(reason);
  9760. }
  9761. });
  9762. };
  9763. InternalPromise.all = function (promises) {
  9764. var newPromise = new InternalPromise();
  9765. var agregator = new FulFillmentAgregator();
  9766. agregator.target = promises.length;
  9767. agregator.rootPromise = newPromise;
  9768. if (promises.length) {
  9769. for (var index = 0; index < promises.length; index++) {
  9770. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9771. }
  9772. }
  9773. else {
  9774. newPromise._resolve([]);
  9775. }
  9776. return newPromise;
  9777. };
  9778. InternalPromise.race = function (promises) {
  9779. var newPromise = new InternalPromise();
  9780. if (promises.length) {
  9781. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9782. var promise = promises_1[_i];
  9783. promise.then(function (value) {
  9784. if (newPromise) {
  9785. newPromise._resolve(value);
  9786. newPromise = null;
  9787. }
  9788. return null;
  9789. }, function (reason) {
  9790. if (newPromise) {
  9791. newPromise._reject(reason);
  9792. newPromise = null;
  9793. }
  9794. });
  9795. }
  9796. }
  9797. return newPromise;
  9798. };
  9799. return InternalPromise;
  9800. }());
  9801. /**
  9802. * Helper class that provides a small promise polyfill
  9803. */
  9804. var PromisePolyfill = /** @class */ (function () {
  9805. function PromisePolyfill() {
  9806. }
  9807. /**
  9808. * Static function used to check if the polyfill is required
  9809. * If this is the case then the function will inject the polyfill to window.Promise
  9810. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9811. */
  9812. PromisePolyfill.Apply = function (force) {
  9813. if (force === void 0) { force = false; }
  9814. if (force || typeof Promise === 'undefined') {
  9815. var root = window;
  9816. root.Promise = InternalPromise;
  9817. }
  9818. };
  9819. return PromisePolyfill;
  9820. }());
  9821. BABYLON.PromisePolyfill = PromisePolyfill;
  9822. })(BABYLON || (BABYLON = {}));
  9823. //# sourceMappingURL=babylon.promise.js.map
  9824. "use strict";
  9825. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9826. var BABYLON;
  9827. (function (BABYLON) {
  9828. /**
  9829. * Helper class to push actions to a pool of workers.
  9830. */
  9831. var WorkerPool = /** @class */ (function () {
  9832. /**
  9833. * Constructor
  9834. * @param workers Array of workers to use for actions
  9835. */
  9836. function WorkerPool(workers) {
  9837. this._pendingActions = new Array();
  9838. this._workerInfos = workers.map(function (worker) { return ({
  9839. worker: worker,
  9840. active: false
  9841. }); });
  9842. }
  9843. /**
  9844. * Terminates all workers and clears any pending actions.
  9845. */
  9846. WorkerPool.prototype.dispose = function () {
  9847. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9848. var workerInfo = _a[_i];
  9849. workerInfo.worker.terminate();
  9850. }
  9851. delete this._workerInfos;
  9852. delete this._pendingActions;
  9853. };
  9854. /**
  9855. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9856. * pended until a worker has completed its action.
  9857. * @param action The action to perform. Call onComplete when the action is complete.
  9858. */
  9859. WorkerPool.prototype.push = function (action) {
  9860. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9861. var workerInfo = _a[_i];
  9862. if (!workerInfo.active) {
  9863. this._execute(workerInfo, action);
  9864. return;
  9865. }
  9866. }
  9867. this._pendingActions.push(action);
  9868. };
  9869. WorkerPool.prototype._execute = function (workerInfo, action) {
  9870. var _this = this;
  9871. workerInfo.active = true;
  9872. action(workerInfo.worker, function () {
  9873. workerInfo.active = false;
  9874. var nextAction = _this._pendingActions.shift();
  9875. if (nextAction) {
  9876. _this._execute(workerInfo, nextAction);
  9877. }
  9878. });
  9879. };
  9880. return WorkerPool;
  9881. }());
  9882. BABYLON.WorkerPool = WorkerPool;
  9883. })(BABYLON || (BABYLON = {}));
  9884. //# sourceMappingURL=babylon.workerPool.js.map
  9885. "use strict";
  9886. var BABYLON;
  9887. (function (BABYLON) {
  9888. var _AlphaState = /** @class */ (function () {
  9889. /**
  9890. * Initializes the state.
  9891. */
  9892. function _AlphaState() {
  9893. this._isAlphaBlendDirty = false;
  9894. this._isBlendFunctionParametersDirty = false;
  9895. this._isBlendEquationParametersDirty = false;
  9896. this._isBlendConstantsDirty = false;
  9897. this._alphaBlend = false;
  9898. this._blendFunctionParameters = new Array(4);
  9899. this._blendEquationParameters = new Array(2);
  9900. this._blendConstants = new Array(4);
  9901. this.reset();
  9902. }
  9903. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9904. get: function () {
  9905. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9911. get: function () {
  9912. return this._alphaBlend;
  9913. },
  9914. set: function (value) {
  9915. if (this._alphaBlend === value) {
  9916. return;
  9917. }
  9918. this._alphaBlend = value;
  9919. this._isAlphaBlendDirty = true;
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9925. if (this._blendConstants[0] === r &&
  9926. this._blendConstants[1] === g &&
  9927. this._blendConstants[2] === b &&
  9928. this._blendConstants[3] === a) {
  9929. return;
  9930. }
  9931. this._blendConstants[0] = r;
  9932. this._blendConstants[1] = g;
  9933. this._blendConstants[2] = b;
  9934. this._blendConstants[3] = a;
  9935. this._isBlendConstantsDirty = true;
  9936. };
  9937. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9938. if (this._blendFunctionParameters[0] === value0 &&
  9939. this._blendFunctionParameters[1] === value1 &&
  9940. this._blendFunctionParameters[2] === value2 &&
  9941. this._blendFunctionParameters[3] === value3) {
  9942. return;
  9943. }
  9944. this._blendFunctionParameters[0] = value0;
  9945. this._blendFunctionParameters[1] = value1;
  9946. this._blendFunctionParameters[2] = value2;
  9947. this._blendFunctionParameters[3] = value3;
  9948. this._isBlendFunctionParametersDirty = true;
  9949. };
  9950. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9951. if (this._blendEquationParameters[0] === rgb &&
  9952. this._blendEquationParameters[1] === alpha) {
  9953. return;
  9954. }
  9955. this._blendEquationParameters[0] = rgb;
  9956. this._blendEquationParameters[1] = alpha;
  9957. this._isBlendEquationParametersDirty = true;
  9958. };
  9959. _AlphaState.prototype.reset = function () {
  9960. this._alphaBlend = false;
  9961. this._blendFunctionParameters[0] = null;
  9962. this._blendFunctionParameters[1] = null;
  9963. this._blendFunctionParameters[2] = null;
  9964. this._blendFunctionParameters[3] = null;
  9965. this._blendEquationParameters[0] = null;
  9966. this._blendEquationParameters[1] = null;
  9967. this._blendConstants[0] = null;
  9968. this._blendConstants[1] = null;
  9969. this._blendConstants[2] = null;
  9970. this._blendConstants[3] = null;
  9971. this._isAlphaBlendDirty = true;
  9972. this._isBlendFunctionParametersDirty = false;
  9973. this._isBlendEquationParametersDirty = false;
  9974. this._isBlendConstantsDirty = false;
  9975. };
  9976. _AlphaState.prototype.apply = function (gl) {
  9977. if (!this.isDirty) {
  9978. return;
  9979. }
  9980. // Alpha blend
  9981. if (this._isAlphaBlendDirty) {
  9982. if (this._alphaBlend) {
  9983. gl.enable(gl.BLEND);
  9984. }
  9985. else {
  9986. gl.disable(gl.BLEND);
  9987. }
  9988. this._isAlphaBlendDirty = false;
  9989. }
  9990. // Alpha function
  9991. if (this._isBlendFunctionParametersDirty) {
  9992. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9993. this._isBlendFunctionParametersDirty = false;
  9994. }
  9995. // Alpha equation
  9996. if (this._isBlendEquationParametersDirty) {
  9997. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9998. this._isBlendEquationParametersDirty = false;
  9999. }
  10000. // Constants
  10001. if (this._isBlendConstantsDirty) {
  10002. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10003. this._isBlendConstantsDirty = false;
  10004. }
  10005. };
  10006. return _AlphaState;
  10007. }());
  10008. BABYLON._AlphaState = _AlphaState;
  10009. })(BABYLON || (BABYLON = {}));
  10010. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10011. "use strict";
  10012. var BABYLON;
  10013. (function (BABYLON) {
  10014. var _DepthCullingState = /** @class */ (function () {
  10015. /**
  10016. * Initializes the state.
  10017. */
  10018. function _DepthCullingState() {
  10019. this._isDepthTestDirty = false;
  10020. this._isDepthMaskDirty = false;
  10021. this._isDepthFuncDirty = false;
  10022. this._isCullFaceDirty = false;
  10023. this._isCullDirty = false;
  10024. this._isZOffsetDirty = false;
  10025. this._isFrontFaceDirty = false;
  10026. this.reset();
  10027. }
  10028. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10029. get: function () {
  10030. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10031. },
  10032. enumerable: true,
  10033. configurable: true
  10034. });
  10035. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10036. get: function () {
  10037. return this._zOffset;
  10038. },
  10039. set: function (value) {
  10040. if (this._zOffset === value) {
  10041. return;
  10042. }
  10043. this._zOffset = value;
  10044. this._isZOffsetDirty = true;
  10045. },
  10046. enumerable: true,
  10047. configurable: true
  10048. });
  10049. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10050. get: function () {
  10051. return this._cullFace;
  10052. },
  10053. set: function (value) {
  10054. if (this._cullFace === value) {
  10055. return;
  10056. }
  10057. this._cullFace = value;
  10058. this._isCullFaceDirty = true;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10064. get: function () {
  10065. return this._cull;
  10066. },
  10067. set: function (value) {
  10068. if (this._cull === value) {
  10069. return;
  10070. }
  10071. this._cull = value;
  10072. this._isCullDirty = true;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10078. get: function () {
  10079. return this._depthFunc;
  10080. },
  10081. set: function (value) {
  10082. if (this._depthFunc === value) {
  10083. return;
  10084. }
  10085. this._depthFunc = value;
  10086. this._isDepthFuncDirty = true;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10092. get: function () {
  10093. return this._depthMask;
  10094. },
  10095. set: function (value) {
  10096. if (this._depthMask === value) {
  10097. return;
  10098. }
  10099. this._depthMask = value;
  10100. this._isDepthMaskDirty = true;
  10101. },
  10102. enumerable: true,
  10103. configurable: true
  10104. });
  10105. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10106. get: function () {
  10107. return this._depthTest;
  10108. },
  10109. set: function (value) {
  10110. if (this._depthTest === value) {
  10111. return;
  10112. }
  10113. this._depthTest = value;
  10114. this._isDepthTestDirty = true;
  10115. },
  10116. enumerable: true,
  10117. configurable: true
  10118. });
  10119. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10120. get: function () {
  10121. return this._frontFace;
  10122. },
  10123. set: function (value) {
  10124. if (this._frontFace === value) {
  10125. return;
  10126. }
  10127. this._frontFace = value;
  10128. this._isFrontFaceDirty = true;
  10129. },
  10130. enumerable: true,
  10131. configurable: true
  10132. });
  10133. _DepthCullingState.prototype.reset = function () {
  10134. this._depthMask = true;
  10135. this._depthTest = true;
  10136. this._depthFunc = null;
  10137. this._cullFace = null;
  10138. this._cull = null;
  10139. this._zOffset = 0;
  10140. this._frontFace = null;
  10141. this._isDepthTestDirty = true;
  10142. this._isDepthMaskDirty = true;
  10143. this._isDepthFuncDirty = false;
  10144. this._isCullFaceDirty = false;
  10145. this._isCullDirty = false;
  10146. this._isZOffsetDirty = false;
  10147. this._isFrontFaceDirty = false;
  10148. };
  10149. _DepthCullingState.prototype.apply = function (gl) {
  10150. if (!this.isDirty) {
  10151. return;
  10152. }
  10153. // Cull
  10154. if (this._isCullDirty) {
  10155. if (this.cull) {
  10156. gl.enable(gl.CULL_FACE);
  10157. }
  10158. else {
  10159. gl.disable(gl.CULL_FACE);
  10160. }
  10161. this._isCullDirty = false;
  10162. }
  10163. // Cull face
  10164. if (this._isCullFaceDirty) {
  10165. gl.cullFace(this.cullFace);
  10166. this._isCullFaceDirty = false;
  10167. }
  10168. // Depth mask
  10169. if (this._isDepthMaskDirty) {
  10170. gl.depthMask(this.depthMask);
  10171. this._isDepthMaskDirty = false;
  10172. }
  10173. // Depth test
  10174. if (this._isDepthTestDirty) {
  10175. if (this.depthTest) {
  10176. gl.enable(gl.DEPTH_TEST);
  10177. }
  10178. else {
  10179. gl.disable(gl.DEPTH_TEST);
  10180. }
  10181. this._isDepthTestDirty = false;
  10182. }
  10183. // Depth func
  10184. if (this._isDepthFuncDirty) {
  10185. gl.depthFunc(this.depthFunc);
  10186. this._isDepthFuncDirty = false;
  10187. }
  10188. // zOffset
  10189. if (this._isZOffsetDirty) {
  10190. if (this.zOffset) {
  10191. gl.enable(gl.POLYGON_OFFSET_FILL);
  10192. gl.polygonOffset(this.zOffset, 0);
  10193. }
  10194. else {
  10195. gl.disable(gl.POLYGON_OFFSET_FILL);
  10196. }
  10197. this._isZOffsetDirty = false;
  10198. }
  10199. // Front face
  10200. if (this._isFrontFaceDirty) {
  10201. gl.frontFace(this.frontFace);
  10202. this._isFrontFaceDirty = false;
  10203. }
  10204. };
  10205. return _DepthCullingState;
  10206. }());
  10207. BABYLON._DepthCullingState = _DepthCullingState;
  10208. })(BABYLON || (BABYLON = {}));
  10209. //# sourceMappingURL=babylon.depthCullingState.js.map
  10210. "use strict";
  10211. var BABYLON;
  10212. (function (BABYLON) {
  10213. var _StencilState = /** @class */ (function () {
  10214. function _StencilState() {
  10215. this._isStencilTestDirty = false;
  10216. this._isStencilMaskDirty = false;
  10217. this._isStencilFuncDirty = false;
  10218. this._isStencilOpDirty = false;
  10219. this.reset();
  10220. }
  10221. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10222. get: function () {
  10223. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10229. get: function () {
  10230. return this._stencilFunc;
  10231. },
  10232. set: function (value) {
  10233. if (this._stencilFunc === value) {
  10234. return;
  10235. }
  10236. this._stencilFunc = value;
  10237. this._isStencilFuncDirty = true;
  10238. },
  10239. enumerable: true,
  10240. configurable: true
  10241. });
  10242. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10243. get: function () {
  10244. return this._stencilFuncRef;
  10245. },
  10246. set: function (value) {
  10247. if (this._stencilFuncRef === value) {
  10248. return;
  10249. }
  10250. this._stencilFuncRef = value;
  10251. this._isStencilFuncDirty = true;
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10257. get: function () {
  10258. return this._stencilFuncMask;
  10259. },
  10260. set: function (value) {
  10261. if (this._stencilFuncMask === value) {
  10262. return;
  10263. }
  10264. this._stencilFuncMask = value;
  10265. this._isStencilFuncDirty = true;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10271. get: function () {
  10272. return this._stencilOpStencilFail;
  10273. },
  10274. set: function (value) {
  10275. if (this._stencilOpStencilFail === value) {
  10276. return;
  10277. }
  10278. this._stencilOpStencilFail = value;
  10279. this._isStencilOpDirty = true;
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10285. get: function () {
  10286. return this._stencilOpDepthFail;
  10287. },
  10288. set: function (value) {
  10289. if (this._stencilOpDepthFail === value) {
  10290. return;
  10291. }
  10292. this._stencilOpDepthFail = value;
  10293. this._isStencilOpDirty = true;
  10294. },
  10295. enumerable: true,
  10296. configurable: true
  10297. });
  10298. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10299. get: function () {
  10300. return this._stencilOpStencilDepthPass;
  10301. },
  10302. set: function (value) {
  10303. if (this._stencilOpStencilDepthPass === value) {
  10304. return;
  10305. }
  10306. this._stencilOpStencilDepthPass = value;
  10307. this._isStencilOpDirty = true;
  10308. },
  10309. enumerable: true,
  10310. configurable: true
  10311. });
  10312. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10313. get: function () {
  10314. return this._stencilMask;
  10315. },
  10316. set: function (value) {
  10317. if (this._stencilMask === value) {
  10318. return;
  10319. }
  10320. this._stencilMask = value;
  10321. this._isStencilMaskDirty = true;
  10322. },
  10323. enumerable: true,
  10324. configurable: true
  10325. });
  10326. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10327. get: function () {
  10328. return this._stencilTest;
  10329. },
  10330. set: function (value) {
  10331. if (this._stencilTest === value) {
  10332. return;
  10333. }
  10334. this._stencilTest = value;
  10335. this._isStencilTestDirty = true;
  10336. },
  10337. enumerable: true,
  10338. configurable: true
  10339. });
  10340. _StencilState.prototype.reset = function () {
  10341. this._stencilTest = false;
  10342. this._stencilMask = 0xFF;
  10343. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10344. this._stencilFuncRef = 1;
  10345. this._stencilFuncMask = 0xFF;
  10346. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10347. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10348. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10349. this._isStencilTestDirty = true;
  10350. this._isStencilMaskDirty = true;
  10351. this._isStencilFuncDirty = true;
  10352. this._isStencilOpDirty = true;
  10353. };
  10354. _StencilState.prototype.apply = function (gl) {
  10355. if (!this.isDirty) {
  10356. return;
  10357. }
  10358. // Stencil test
  10359. if (this._isStencilTestDirty) {
  10360. if (this.stencilTest) {
  10361. gl.enable(gl.STENCIL_TEST);
  10362. }
  10363. else {
  10364. gl.disable(gl.STENCIL_TEST);
  10365. }
  10366. this._isStencilTestDirty = false;
  10367. }
  10368. // Stencil mask
  10369. if (this._isStencilMaskDirty) {
  10370. gl.stencilMask(this.stencilMask);
  10371. this._isStencilMaskDirty = false;
  10372. }
  10373. // Stencil func
  10374. if (this._isStencilFuncDirty) {
  10375. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10376. this._isStencilFuncDirty = false;
  10377. }
  10378. // Stencil op
  10379. if (this._isStencilOpDirty) {
  10380. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10381. this._isStencilOpDirty = false;
  10382. }
  10383. };
  10384. return _StencilState;
  10385. }());
  10386. BABYLON._StencilState = _StencilState;
  10387. })(BABYLON || (BABYLON = {}));
  10388. //# sourceMappingURL=babylon.stencilState.js.map
  10389. "use strict";
  10390. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10391. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10392. s = arguments[i];
  10393. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10394. t[p] = s[p];
  10395. }
  10396. return t;
  10397. };
  10398. var BABYLON;
  10399. (function (BABYLON) {
  10400. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10401. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10402. };
  10403. var compileRawShader = function (gl, source, type) {
  10404. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10405. gl.shaderSource(shader, source);
  10406. gl.compileShader(shader);
  10407. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10408. var log = gl.getShaderInfoLog(shader);
  10409. if (log) {
  10410. throw new Error(log);
  10411. }
  10412. }
  10413. if (!shader) {
  10414. throw new Error("Something went wrong while compile the shader.");
  10415. }
  10416. return shader;
  10417. };
  10418. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10419. var magFilter = gl.NEAREST;
  10420. var minFilter = gl.NEAREST;
  10421. switch (samplingMode) {
  10422. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10423. magFilter = gl.LINEAR;
  10424. if (generateMipMaps) {
  10425. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10426. }
  10427. else {
  10428. minFilter = gl.LINEAR;
  10429. }
  10430. break;
  10431. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10432. magFilter = gl.LINEAR;
  10433. if (generateMipMaps) {
  10434. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10435. }
  10436. else {
  10437. minFilter = gl.LINEAR;
  10438. }
  10439. break;
  10440. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10441. magFilter = gl.NEAREST;
  10442. if (generateMipMaps) {
  10443. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10444. }
  10445. else {
  10446. minFilter = gl.NEAREST;
  10447. }
  10448. break;
  10449. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10450. magFilter = gl.NEAREST;
  10451. if (generateMipMaps) {
  10452. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10453. }
  10454. else {
  10455. minFilter = gl.NEAREST;
  10456. }
  10457. break;
  10458. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10459. magFilter = gl.NEAREST;
  10460. if (generateMipMaps) {
  10461. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10462. }
  10463. else {
  10464. minFilter = gl.LINEAR;
  10465. }
  10466. break;
  10467. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10468. magFilter = gl.NEAREST;
  10469. if (generateMipMaps) {
  10470. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10471. }
  10472. else {
  10473. minFilter = gl.LINEAR;
  10474. }
  10475. break;
  10476. case BABYLON.Texture.NEAREST_LINEAR:
  10477. magFilter = gl.NEAREST;
  10478. minFilter = gl.LINEAR;
  10479. break;
  10480. case BABYLON.Texture.NEAREST_NEAREST:
  10481. magFilter = gl.NEAREST;
  10482. minFilter = gl.NEAREST;
  10483. break;
  10484. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10485. magFilter = gl.LINEAR;
  10486. if (generateMipMaps) {
  10487. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10488. }
  10489. else {
  10490. minFilter = gl.NEAREST;
  10491. }
  10492. break;
  10493. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10494. magFilter = gl.LINEAR;
  10495. if (generateMipMaps) {
  10496. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10497. }
  10498. else {
  10499. minFilter = gl.NEAREST;
  10500. }
  10501. break;
  10502. case BABYLON.Texture.LINEAR_LINEAR:
  10503. magFilter = gl.LINEAR;
  10504. minFilter = gl.LINEAR;
  10505. break;
  10506. case BABYLON.Texture.LINEAR_NEAREST:
  10507. magFilter = gl.LINEAR;
  10508. minFilter = gl.NEAREST;
  10509. break;
  10510. }
  10511. return {
  10512. min: minFilter,
  10513. mag: magFilter
  10514. };
  10515. };
  10516. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10517. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10518. var img;
  10519. var onload = function () {
  10520. loadedImages[index] = img;
  10521. loadedImages._internalCount++;
  10522. if (scene) {
  10523. scene._removePendingData(img);
  10524. }
  10525. if (loadedImages._internalCount === 6) {
  10526. onfinish(loadedImages);
  10527. }
  10528. };
  10529. var onerror = function (message, exception) {
  10530. if (scene) {
  10531. scene._removePendingData(img);
  10532. }
  10533. if (onErrorCallBack) {
  10534. onErrorCallBack(message, exception);
  10535. }
  10536. };
  10537. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10538. if (scene) {
  10539. scene._addPendingData(img);
  10540. }
  10541. };
  10542. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10543. if (onError === void 0) { onError = null; }
  10544. var loadedImages = [];
  10545. loadedImages._internalCount = 0;
  10546. for (var index = 0; index < 6; index++) {
  10547. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10548. }
  10549. };
  10550. var BufferPointer = /** @class */ (function () {
  10551. function BufferPointer() {
  10552. }
  10553. return BufferPointer;
  10554. }());
  10555. /**
  10556. * Interface for attribute information associated with buffer instanciation
  10557. */
  10558. var InstancingAttributeInfo = /** @class */ (function () {
  10559. function InstancingAttributeInfo() {
  10560. }
  10561. return InstancingAttributeInfo;
  10562. }());
  10563. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10564. /**
  10565. * Define options used to create a render target texture
  10566. */
  10567. var RenderTargetCreationOptions = /** @class */ (function () {
  10568. function RenderTargetCreationOptions() {
  10569. }
  10570. return RenderTargetCreationOptions;
  10571. }());
  10572. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10573. /**
  10574. * Define options used to create a depth texture
  10575. */
  10576. var DepthTextureCreationOptions = /** @class */ (function () {
  10577. function DepthTextureCreationOptions() {
  10578. }
  10579. return DepthTextureCreationOptions;
  10580. }());
  10581. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10582. /**
  10583. * Class used to describe the capabilities of the engine relatively to the current browser
  10584. */
  10585. var EngineCapabilities = /** @class */ (function () {
  10586. function EngineCapabilities() {
  10587. }
  10588. return EngineCapabilities;
  10589. }());
  10590. BABYLON.EngineCapabilities = EngineCapabilities;
  10591. /**
  10592. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10593. */
  10594. var Engine = /** @class */ (function () {
  10595. /**
  10596. * Creates a new engine
  10597. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10598. * @param antialias defines enable antialiasing (default: false)
  10599. * @param options defines further options to be sent to the getContext() function
  10600. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10601. */
  10602. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10603. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10604. var _this = this;
  10605. // Public members
  10606. /**
  10607. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10608. */
  10609. this.forcePOTTextures = false;
  10610. /**
  10611. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10612. */
  10613. this.isFullscreen = false;
  10614. /**
  10615. * Gets a boolean indicating if the pointer is currently locked
  10616. */
  10617. this.isPointerLock = false;
  10618. /**
  10619. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10620. */
  10621. this.cullBackFaces = true;
  10622. /**
  10623. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10624. */
  10625. this.renderEvenInBackground = true;
  10626. /**
  10627. * Gets or sets a boolean indicating that cache can be kept between frames
  10628. */
  10629. this.preventCacheWipeBetweenFrames = false;
  10630. /**
  10631. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10632. **/
  10633. this.enableOfflineSupport = false;
  10634. /**
  10635. * Gets the list of created scenes
  10636. */
  10637. this.scenes = new Array();
  10638. /**
  10639. * Gets the list of created postprocesses
  10640. */
  10641. this.postProcesses = new Array();
  10642. // Observables
  10643. /**
  10644. * Observable event triggered each time the rendering canvas is resized
  10645. */
  10646. this.onResizeObservable = new BABYLON.Observable();
  10647. /**
  10648. * Observable event triggered each time the canvas loses focus
  10649. */
  10650. this.onCanvasBlurObservable = new BABYLON.Observable();
  10651. /**
  10652. * Observable event triggered each time the canvas gains focus
  10653. */
  10654. this.onCanvasFocusObservable = new BABYLON.Observable();
  10655. /**
  10656. * Observable event triggered each time the canvas receives pointerout event
  10657. */
  10658. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10659. /**
  10660. * Observable event triggered before each texture is initialized
  10661. */
  10662. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10663. //WebVR
  10664. this._vrDisplay = undefined;
  10665. this._vrSupported = false;
  10666. this._vrExclusivePointerMode = false;
  10667. // Uniform buffers list
  10668. /**
  10669. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10670. */
  10671. this.disableUniformBuffers = false;
  10672. /** @ignore */
  10673. this._uniformBuffers = new Array();
  10674. // Observables
  10675. /**
  10676. * Observable raised when the engine begins a new frame
  10677. */
  10678. this.onBeginFrameObservable = new BABYLON.Observable();
  10679. /**
  10680. * Observable raised when the engine ends the current frame
  10681. */
  10682. this.onEndFrameObservable = new BABYLON.Observable();
  10683. /**
  10684. * Observable raised when the engine is about to compile a shader
  10685. */
  10686. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10687. /**
  10688. * Observable raised when the engine has jsut compiled a shader
  10689. */
  10690. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10691. this._windowIsBackground = false;
  10692. this._webGLVersion = 1.0;
  10693. /** @ignore */
  10694. this._badOS = false;
  10695. /** @ignore */
  10696. this._badDesktopOS = false;
  10697. /**
  10698. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10699. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  10700. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  10701. */
  10702. this.disableTextureBindingOptimization = false;
  10703. /**
  10704. * Observable signaled when VR display mode changes
  10705. */
  10706. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10707. /**
  10708. * Observable signaled when VR request present is complete
  10709. */
  10710. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10711. /**
  10712. * Observable signaled when VR request present starts
  10713. */
  10714. this.onVRRequestPresentStart = new BABYLON.Observable();
  10715. this._colorWrite = true;
  10716. /** @ignore */
  10717. this._drawCalls = new BABYLON.PerfCounter();
  10718. /** @ignore */
  10719. this._textureCollisions = new BABYLON.PerfCounter();
  10720. this._renderingQueueLaunched = false;
  10721. this._activeRenderLoops = new Array();
  10722. // Deterministic lockstepMaxSteps
  10723. this._deterministicLockstep = false;
  10724. this._lockstepMaxSteps = 4;
  10725. // Lost context
  10726. /**
  10727. * Observable signaled when a context lost event is raised
  10728. */
  10729. this.onContextLostObservable = new BABYLON.Observable();
  10730. /**
  10731. * Observable signaled when a context restored event is raised
  10732. */
  10733. this.onContextRestoredObservable = new BABYLON.Observable();
  10734. this._contextWasLost = false;
  10735. this._doNotHandleContextLost = false;
  10736. // FPS
  10737. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10738. this._fps = 60;
  10739. this._deltaTime = 0;
  10740. /**
  10741. * Turn this value on if you want to pause FPS computation when in background
  10742. */
  10743. this.disablePerformanceMonitorInBackground = false;
  10744. // States
  10745. /** @ignore */
  10746. this._depthCullingState = new BABYLON._DepthCullingState();
  10747. /** @ignore */
  10748. this._stencilState = new BABYLON._StencilState();
  10749. /** @ignore */
  10750. this._alphaState = new BABYLON._AlphaState();
  10751. /** @ignore */
  10752. this._alphaMode = Engine.ALPHA_DISABLE;
  10753. // Cache
  10754. this._internalTexturesCache = new Array();
  10755. /** @ignore */
  10756. this._activeChannel = 0;
  10757. this._currentTextureChannel = -1;
  10758. /** @ignore */
  10759. this._boundTexturesCache = {};
  10760. this._compiledEffects = {};
  10761. this._vertexAttribArraysEnabled = [];
  10762. this._uintIndicesCurrentlySet = false;
  10763. this._currentBoundBuffer = new Array();
  10764. this._currentBufferPointers = new Array();
  10765. this._currentInstanceLocations = new Array();
  10766. this._currentInstanceBuffers = new Array();
  10767. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10768. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10769. this._vaoRecordInProgress = false;
  10770. this._mustWipeVertexAttributes = false;
  10771. this._nextFreeTextureSlots = new Array();
  10772. this._maxSimultaneousTextures = 0;
  10773. this._activeRequests = new Array();
  10774. // Hardware supported Compressed Textures
  10775. this._texturesSupported = new Array();
  10776. this._onVRFullScreenTriggered = function () {
  10777. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10778. //get the old size before we change
  10779. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10780. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10781. //get the width and height, change the render size
  10782. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10783. _this.setHardwareScalingLevel(1);
  10784. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10785. }
  10786. else {
  10787. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10788. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10789. }
  10790. };
  10791. this._boundUniforms = {};
  10792. // Register promises
  10793. BABYLON.PromisePolyfill.Apply();
  10794. var canvas = null;
  10795. Engine.Instances.push(this);
  10796. if (!canvasOrContext) {
  10797. return;
  10798. }
  10799. options = options || {};
  10800. if (canvasOrContext.getContext) {
  10801. canvas = canvasOrContext;
  10802. this._renderingCanvas = canvas;
  10803. if (antialias != null) {
  10804. options.antialias = antialias;
  10805. }
  10806. if (options.deterministicLockstep === undefined) {
  10807. options.deterministicLockstep = false;
  10808. }
  10809. if (options.lockstepMaxSteps === undefined) {
  10810. options.lockstepMaxSteps = 4;
  10811. }
  10812. if (options.preserveDrawingBuffer === undefined) {
  10813. options.preserveDrawingBuffer = false;
  10814. }
  10815. if (options.audioEngine === undefined) {
  10816. options.audioEngine = true;
  10817. }
  10818. if (options.stencil === undefined) {
  10819. options.stencil = true;
  10820. }
  10821. this._deterministicLockstep = options.deterministicLockstep;
  10822. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10823. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10824. // Exceptions
  10825. if (navigator && navigator.userAgent) {
  10826. var ua = navigator.userAgent;
  10827. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10828. var exception = _a[_i];
  10829. var key = exception.key;
  10830. var targets = exception.targets;
  10831. if (ua.indexOf(key) > -1) {
  10832. if (exception.capture && exception.captureConstraint) {
  10833. var capture = exception.capture;
  10834. var constraint = exception.captureConstraint;
  10835. var regex = new RegExp(capture);
  10836. var matches = regex.exec(ua);
  10837. if (matches && matches.length > 0) {
  10838. var capturedValue = parseInt(matches[matches.length - 1]);
  10839. if (capturedValue >= constraint) {
  10840. continue;
  10841. }
  10842. }
  10843. }
  10844. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10845. var target = targets_1[_b];
  10846. switch (target) {
  10847. case "uniformBuffer":
  10848. this.disableUniformBuffers = true;
  10849. break;
  10850. case "textureBindingOptimization":
  10851. this.disableTextureBindingOptimization = true;
  10852. break;
  10853. }
  10854. }
  10855. }
  10856. }
  10857. }
  10858. // GL
  10859. if (!options.disableWebGL2Support) {
  10860. try {
  10861. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10862. if (this._gl) {
  10863. this._webGLVersion = 2.0;
  10864. }
  10865. }
  10866. catch (e) {
  10867. // Do nothing
  10868. }
  10869. }
  10870. if (!this._gl) {
  10871. if (!canvas) {
  10872. throw new Error("The provided canvas is null or undefined.");
  10873. }
  10874. try {
  10875. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10876. }
  10877. catch (e) {
  10878. throw new Error("WebGL not supported");
  10879. }
  10880. }
  10881. if (!this._gl) {
  10882. throw new Error("WebGL not supported");
  10883. }
  10884. this._onCanvasFocus = function () {
  10885. _this.onCanvasFocusObservable.notifyObservers(_this);
  10886. };
  10887. this._onCanvasBlur = function () {
  10888. _this.onCanvasBlurObservable.notifyObservers(_this);
  10889. };
  10890. canvas.addEventListener("focus", this._onCanvasFocus);
  10891. canvas.addEventListener("blur", this._onCanvasBlur);
  10892. this._onBlur = function () {
  10893. if (_this.disablePerformanceMonitorInBackground) {
  10894. _this._performanceMonitor.disable();
  10895. }
  10896. _this._windowIsBackground = true;
  10897. };
  10898. this._onFocus = function () {
  10899. if (_this.disablePerformanceMonitorInBackground) {
  10900. _this._performanceMonitor.enable();
  10901. }
  10902. _this._windowIsBackground = false;
  10903. };
  10904. this._onCanvasPointerOut = function (ev) {
  10905. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10906. };
  10907. window.addEventListener("blur", this._onBlur);
  10908. window.addEventListener("focus", this._onFocus);
  10909. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10910. // Context lost
  10911. if (!this._doNotHandleContextLost) {
  10912. this._onContextLost = function (evt) {
  10913. evt.preventDefault();
  10914. _this._contextWasLost = true;
  10915. BABYLON.Tools.Warn("WebGL context lost.");
  10916. _this.onContextLostObservable.notifyObservers(_this);
  10917. };
  10918. this._onContextRestored = function (evt) {
  10919. // Adding a timeout to avoid race condition at browser level
  10920. setTimeout(function () {
  10921. // Rebuild gl context
  10922. _this._initGLContext();
  10923. // Rebuild effects
  10924. _this._rebuildEffects();
  10925. // Rebuild textures
  10926. _this._rebuildInternalTextures();
  10927. // Rebuild buffers
  10928. _this._rebuildBuffers();
  10929. // Cache
  10930. _this.wipeCaches(true);
  10931. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10932. _this.onContextRestoredObservable.notifyObservers(_this);
  10933. _this._contextWasLost = false;
  10934. }, 0);
  10935. };
  10936. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10937. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10938. }
  10939. }
  10940. else {
  10941. this._gl = canvasOrContext;
  10942. this._renderingCanvas = this._gl.canvas;
  10943. if (this._gl.renderbufferStorageMultisample) {
  10944. this._webGLVersion = 2.0;
  10945. }
  10946. options.stencil = this._gl.getContextAttributes().stencil;
  10947. }
  10948. // Viewport
  10949. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10950. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10951. this.resize();
  10952. this._isStencilEnable = options.stencil ? true : false;
  10953. this._initGLContext();
  10954. if (canvas) {
  10955. // Fullscreen
  10956. this._onFullscreenChange = function () {
  10957. if (document.fullscreen !== undefined) {
  10958. _this.isFullscreen = document.fullscreen;
  10959. }
  10960. else if (document.mozFullScreen !== undefined) {
  10961. _this.isFullscreen = document.mozFullScreen;
  10962. }
  10963. else if (document.webkitIsFullScreen !== undefined) {
  10964. _this.isFullscreen = document.webkitIsFullScreen;
  10965. }
  10966. else if (document.msIsFullScreen !== undefined) {
  10967. _this.isFullscreen = document.msIsFullScreen;
  10968. }
  10969. // Pointer lock
  10970. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10971. canvas.requestPointerLock = canvas.requestPointerLock ||
  10972. canvas.msRequestPointerLock ||
  10973. canvas.mozRequestPointerLock ||
  10974. canvas.webkitRequestPointerLock;
  10975. if (canvas.requestPointerLock) {
  10976. canvas.requestPointerLock();
  10977. }
  10978. }
  10979. };
  10980. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10981. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10982. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10983. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10984. // Pointer lock
  10985. this._onPointerLockChange = function () {
  10986. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10987. document.webkitPointerLockElement === canvas ||
  10988. document.msPointerLockElement === canvas ||
  10989. document.pointerLockElement === canvas);
  10990. };
  10991. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10992. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10993. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10994. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10995. this._onVRDisplayPointerRestricted = function () {
  10996. if (canvas) {
  10997. canvas.requestPointerLock();
  10998. }
  10999. };
  11000. this._onVRDisplayPointerUnrestricted = function () {
  11001. document.exitPointerLock();
  11002. };
  11003. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11004. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11005. }
  11006. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11007. Engine.audioEngine = new BABYLON.AudioEngine();
  11008. }
  11009. // Prepare buffer pointers
  11010. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11011. this._currentBufferPointers[i] = new BufferPointer();
  11012. }
  11013. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11014. // Load WebVR Devices
  11015. if (options.autoEnableWebVR) {
  11016. this.initWebVR();
  11017. }
  11018. // Detect if we are running on a faulty buggy OS.
  11019. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11020. // Detect if we are running on a faulty buggy desktop OS.
  11021. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11022. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11023. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11024. }
  11025. Object.defineProperty(Engine, "LastCreatedEngine", {
  11026. /**
  11027. * Gets the latest created engine
  11028. */
  11029. get: function () {
  11030. if (Engine.Instances.length === 0) {
  11031. return null;
  11032. }
  11033. return Engine.Instances[Engine.Instances.length - 1];
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "LastCreatedScene", {
  11039. /**
  11040. * Gets the latest created scene
  11041. */
  11042. get: function () {
  11043. var lastCreatedEngine = Engine.LastCreatedEngine;
  11044. if (!lastCreatedEngine) {
  11045. return null;
  11046. }
  11047. if (lastCreatedEngine.scenes.length === 0) {
  11048. return null;
  11049. }
  11050. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. /**
  11056. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11057. * @param flag defines which part of the materials must be marked as dirty
  11058. * @param predicate defines a predicate used to filter which materials should be affected
  11059. */
  11060. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11061. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11062. var engine = Engine.Instances[engineIndex];
  11063. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11064. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11065. }
  11066. }
  11067. };
  11068. Object.defineProperty(Engine, "NEVER", {
  11069. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11070. get: function () {
  11071. return Engine._NEVER;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Object.defineProperty(Engine, "ALWAYS", {
  11077. /** 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 */
  11078. get: function () {
  11079. return Engine._ALWAYS;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine, "LESS", {
  11085. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11086. get: function () {
  11087. return Engine._LESS;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "EQUAL", {
  11093. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11094. get: function () {
  11095. return Engine._EQUAL;
  11096. },
  11097. enumerable: true,
  11098. configurable: true
  11099. });
  11100. Object.defineProperty(Engine, "LEQUAL", {
  11101. /** 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 */
  11102. get: function () {
  11103. return Engine._LEQUAL;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Engine, "GREATER", {
  11109. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11110. get: function () {
  11111. return Engine._GREATER;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "GEQUAL", {
  11117. /** 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 */
  11118. get: function () {
  11119. return Engine._GEQUAL;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Engine, "NOTEQUAL", {
  11125. /** 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 */
  11126. get: function () {
  11127. return Engine._NOTEQUAL;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(Engine, "KEEP", {
  11133. /** Passed to stencilOperation to specify that stencil value must be kept */
  11134. get: function () {
  11135. return Engine._KEEP;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine, "REPLACE", {
  11141. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11142. get: function () {
  11143. return Engine._REPLACE;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "INCR", {
  11149. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11150. get: function () {
  11151. return Engine._INCR;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "DECR", {
  11157. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11158. get: function () {
  11159. return Engine._DECR;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine, "INVERT", {
  11165. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11166. get: function () {
  11167. return Engine._INVERT;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "INCR_WRAP", {
  11173. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11174. get: function () {
  11175. return Engine._INCR_WRAP;
  11176. },
  11177. enumerable: true,
  11178. configurable: true
  11179. });
  11180. Object.defineProperty(Engine, "DECR_WRAP", {
  11181. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11182. get: function () {
  11183. return Engine._DECR_WRAP;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11189. // Alpha
  11190. /** Defines that alpha blending is disabled */
  11191. get: function () {
  11192. return Engine._ALPHA_DISABLE;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11198. /** Defines that alpha blending to SRC + DEST */
  11199. get: function () {
  11200. return Engine._ALPHA_ONEONE;
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine, "ALPHA_ADD", {
  11206. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11207. get: function () {
  11208. return Engine._ALPHA_ADD;
  11209. },
  11210. enumerable: true,
  11211. configurable: true
  11212. });
  11213. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11214. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11215. get: function () {
  11216. return Engine._ALPHA_COMBINE;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11222. /** Defines that alpha blending to DEST - SRC * DEST */
  11223. get: function () {
  11224. return Engine._ALPHA_SUBTRACT;
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11230. /** Defines that alpha blending to SRC * DEST */
  11231. get: function () {
  11232. return Engine._ALPHA_MULTIPLY;
  11233. },
  11234. enumerable: true,
  11235. configurable: true
  11236. });
  11237. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11238. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11239. get: function () {
  11240. return Engine._ALPHA_MAXIMIZED;
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11246. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11247. get: function () {
  11248. return Engine._ALPHA_PREMULTIPLIED;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11254. /**
  11255. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11256. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11257. */
  11258. get: function () {
  11259. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11260. },
  11261. enumerable: true,
  11262. configurable: true
  11263. });
  11264. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11265. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11266. get: function () {
  11267. return Engine._ALPHA_INTERPOLATE;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11273. /**
  11274. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11275. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11276. */
  11277. get: function () {
  11278. return Engine._ALPHA_SCREENMODE;
  11279. },
  11280. enumerable: true,
  11281. configurable: true
  11282. });
  11283. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11284. // Delays
  11285. /** Defines that the ressource is not delayed*/
  11286. get: function () {
  11287. return Engine._DELAYLOADSTATE_NONE;
  11288. },
  11289. enumerable: true,
  11290. configurable: true
  11291. });
  11292. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11293. /** Defines that the ressource was successfully delay loaded */
  11294. get: function () {
  11295. return Engine._DELAYLOADSTATE_LOADED;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11301. /** Defines that the ressource is currently delay loading */
  11302. get: function () {
  11303. return Engine._DELAYLOADSTATE_LOADING;
  11304. },
  11305. enumerable: true,
  11306. configurable: true
  11307. });
  11308. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11309. /** Defines that the ressource is delayed and has not started loading */
  11310. get: function () {
  11311. return Engine._DELAYLOADSTATE_NOTLOADED;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11317. /** ALPHA */
  11318. get: function () {
  11319. return Engine._TEXTUREFORMAT_ALPHA;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11325. /** LUMINANCE */
  11326. get: function () {
  11327. return Engine._TEXTUREFORMAT_LUMINANCE;
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11333. /**
  11334. * R32F
  11335. */
  11336. get: function () {
  11337. return Engine._TEXTUREFORMAT_R32F;
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11343. /**
  11344. * RG32F
  11345. */
  11346. get: function () {
  11347. return Engine._TEXTUREFORMAT_RG32F;
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11353. /**
  11354. * RGB32F
  11355. */
  11356. get: function () {
  11357. return Engine._TEXTUREFORMAT_RGB32F;
  11358. },
  11359. enumerable: true,
  11360. configurable: true
  11361. });
  11362. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11363. /**
  11364. * RGBA32F
  11365. */
  11366. get: function () {
  11367. return Engine._TEXTUREFORMAT_RGBA32F;
  11368. },
  11369. enumerable: true,
  11370. configurable: true
  11371. });
  11372. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11373. /** LUMINANCE_ALPHA */
  11374. get: function () {
  11375. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11381. /** RGB */
  11382. get: function () {
  11383. return Engine._TEXTUREFORMAT_RGB;
  11384. },
  11385. enumerable: true,
  11386. configurable: true
  11387. });
  11388. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11389. /** RGBA */
  11390. get: function () {
  11391. return Engine._TEXTUREFORMAT_RGBA;
  11392. },
  11393. enumerable: true,
  11394. configurable: true
  11395. });
  11396. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11397. /** UNSIGNED_INT */
  11398. get: function () {
  11399. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11405. /** FLOAT */
  11406. get: function () {
  11407. return Engine._TEXTURETYPE_FLOAT;
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11413. /** HALF_FLOAT */
  11414. get: function () {
  11415. return Engine._TEXTURETYPE_HALF_FLOAT;
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11421. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11422. get: function () {
  11423. return Engine._SCALEMODE_FLOOR;
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11429. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11430. get: function () {
  11431. return Engine._SCALEMODE_NEAREST;
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11437. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11438. get: function () {
  11439. return Engine._SCALEMODE_CEILING;
  11440. },
  11441. enumerable: true,
  11442. configurable: true
  11443. });
  11444. Object.defineProperty(Engine, "Version", {
  11445. /**
  11446. * Returns the current version of the framework
  11447. */
  11448. get: function () {
  11449. return "3.2.0-beta.3";
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11455. /**
  11456. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11457. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11458. */
  11459. get: function () {
  11460. return this._vrExclusivePointerMode;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11466. /**
  11467. * Gets a boolean indicating that the engine supports uniform buffers
  11468. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11469. */
  11470. get: function () {
  11471. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11472. },
  11473. enumerable: true,
  11474. configurable: true
  11475. });
  11476. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11477. /**
  11478. * Gets a boolean indicating that only power of 2 textures are supported
  11479. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11480. */
  11481. get: function () {
  11482. return this._webGLVersion < 2 || this.forcePOTTextures;
  11483. },
  11484. enumerable: true,
  11485. configurable: true
  11486. });
  11487. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11488. /**
  11489. * Gets the performance monitor attached to this engine
  11490. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11491. */
  11492. get: function () {
  11493. return this._performanceMonitor;
  11494. },
  11495. enumerable: true,
  11496. configurable: true
  11497. });
  11498. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11499. /**
  11500. * Gets the list of texture formats supported
  11501. */
  11502. get: function () {
  11503. return this._texturesSupported;
  11504. },
  11505. enumerable: true,
  11506. configurable: true
  11507. });
  11508. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11509. /**
  11510. * Gets the list of texture formats in use
  11511. */
  11512. get: function () {
  11513. return this._textureFormatInUse;
  11514. },
  11515. enumerable: true,
  11516. configurable: true
  11517. });
  11518. Object.defineProperty(Engine.prototype, "currentViewport", {
  11519. /**
  11520. * Gets the current viewport
  11521. */
  11522. get: function () {
  11523. return this._cachedViewport;
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11529. /**
  11530. * Gets the default empty texture
  11531. */
  11532. get: function () {
  11533. if (!this._emptyTexture) {
  11534. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11535. }
  11536. return this._emptyTexture;
  11537. },
  11538. enumerable: true,
  11539. configurable: true
  11540. });
  11541. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11542. /**
  11543. * Gets the default empty 3D texture
  11544. */
  11545. get: function () {
  11546. if (!this._emptyTexture3D) {
  11547. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11548. }
  11549. return this._emptyTexture3D;
  11550. },
  11551. enumerable: true,
  11552. configurable: true
  11553. });
  11554. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11555. /**
  11556. * Gets the default empty cube texture
  11557. */
  11558. get: function () {
  11559. if (!this._emptyCubeTexture) {
  11560. var faceData = new Uint8Array(4);
  11561. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11562. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11563. }
  11564. return this._emptyCubeTexture;
  11565. },
  11566. enumerable: true,
  11567. configurable: true
  11568. });
  11569. Engine.prototype._rebuildInternalTextures = function () {
  11570. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11571. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11572. var internalTexture = currentState_1[_i];
  11573. internalTexture._rebuild();
  11574. }
  11575. };
  11576. Engine.prototype._rebuildEffects = function () {
  11577. for (var key in this._compiledEffects) {
  11578. var effect = this._compiledEffects[key];
  11579. effect._prepareEffect();
  11580. }
  11581. BABYLON.Effect.ResetCache();
  11582. };
  11583. Engine.prototype._rebuildBuffers = function () {
  11584. // Index / Vertex
  11585. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11586. var scene = _a[_i];
  11587. scene.resetCachedMaterial();
  11588. scene._rebuildGeometries();
  11589. scene._rebuildTextures();
  11590. }
  11591. // Uniforms
  11592. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11593. var uniformBuffer = _c[_b];
  11594. uniformBuffer._rebuild();
  11595. }
  11596. };
  11597. Engine.prototype._initGLContext = function () {
  11598. // Caps
  11599. this._caps = new EngineCapabilities();
  11600. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11601. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11602. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11603. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11604. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11605. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11606. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11607. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11608. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11609. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11610. // Infos
  11611. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11612. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11613. if (rendererInfo != null) {
  11614. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11615. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11616. }
  11617. if (!this._glVendor) {
  11618. this._glVendor = "Unknown vendor";
  11619. }
  11620. if (!this._glRenderer) {
  11621. this._glRenderer = "Unknown renderer";
  11622. }
  11623. // Constants
  11624. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11625. if (this._gl.RGBA16F !== 0x881A) {
  11626. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11627. }
  11628. if (this._gl.RGBA32F !== 0x8814) {
  11629. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11630. }
  11631. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11632. this._gl.DEPTH24_STENCIL8 = 35056;
  11633. }
  11634. // Extensions
  11635. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11636. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11637. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11638. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11639. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11640. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11641. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11642. 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');
  11643. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11644. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11645. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11646. this._caps.highPrecisionShaderSupported = true;
  11647. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11648. if (this._caps.timerQuery) {
  11649. if (this._webGLVersion === 1) {
  11650. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11651. }
  11652. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11653. }
  11654. // Checks if some of the format renders first to allow the use of webgl inspector.
  11655. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11656. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11657. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11658. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11659. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11660. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11661. if (this._webGLVersion > 1) {
  11662. this._gl.HALF_FLOAT_OES = 0x140B;
  11663. }
  11664. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11665. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11666. // Draw buffers
  11667. if (this._webGLVersion > 1) {
  11668. this._caps.drawBuffersExtension = true;
  11669. }
  11670. else {
  11671. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11672. if (drawBuffersExtension !== null) {
  11673. this._caps.drawBuffersExtension = true;
  11674. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11675. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11676. for (var i = 0; i < 16; i++) {
  11677. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11678. }
  11679. }
  11680. else {
  11681. this._caps.drawBuffersExtension = false;
  11682. }
  11683. }
  11684. // Depth Texture
  11685. if (this._webGLVersion > 1) {
  11686. this._caps.depthTextureExtension = true;
  11687. }
  11688. else {
  11689. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11690. if (depthTextureExtension != null) {
  11691. this._caps.depthTextureExtension = true;
  11692. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11693. }
  11694. }
  11695. // Vertex array object
  11696. if (this._webGLVersion > 1) {
  11697. this._caps.vertexArrayObject = true;
  11698. }
  11699. else {
  11700. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11701. if (vertexArrayObjectExtension != null) {
  11702. this._caps.vertexArrayObject = true;
  11703. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11704. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11705. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11706. }
  11707. else {
  11708. this._caps.vertexArrayObject = false;
  11709. }
  11710. }
  11711. // Instances count
  11712. if (this._webGLVersion > 1) {
  11713. this._caps.instancedArrays = true;
  11714. }
  11715. else {
  11716. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11717. if (instanceExtension != null) {
  11718. this._caps.instancedArrays = true;
  11719. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11720. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11721. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11722. }
  11723. else {
  11724. this._caps.instancedArrays = false;
  11725. }
  11726. }
  11727. // Intelligently add supported compressed formats in order to check for.
  11728. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11729. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11730. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11731. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11732. if (this._caps.astc)
  11733. this.texturesSupported.push('-astc.ktx');
  11734. if (this._caps.s3tc)
  11735. this.texturesSupported.push('-dxt.ktx');
  11736. if (this._caps.pvrtc)
  11737. this.texturesSupported.push('-pvrtc.ktx');
  11738. if (this._caps.etc2)
  11739. this.texturesSupported.push('-etc2.ktx');
  11740. if (this._caps.etc1)
  11741. this.texturesSupported.push('-etc1.ktx');
  11742. if (this._gl.getShaderPrecisionFormat) {
  11743. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11744. if (highp) {
  11745. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11746. }
  11747. }
  11748. // Depth buffer
  11749. this.setDepthBuffer(true);
  11750. this.setDepthFunctionToLessOrEqual();
  11751. this.setDepthWrite(true);
  11752. // Texture maps
  11753. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11754. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11755. this._nextFreeTextureSlots.push(slot);
  11756. }
  11757. };
  11758. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11759. /**
  11760. * Gets version of the current webGL context
  11761. */
  11762. get: function () {
  11763. return this._webGLVersion;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11769. /**
  11770. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11771. */
  11772. get: function () {
  11773. return this._isStencilEnable;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Engine.prototype._prepareWorkingCanvas = function () {
  11779. if (this._workingCanvas) {
  11780. return;
  11781. }
  11782. this._workingCanvas = document.createElement("canvas");
  11783. var context = this._workingCanvas.getContext("2d");
  11784. if (context) {
  11785. this._workingContext = context;
  11786. }
  11787. };
  11788. /**
  11789. * Reset the texture cache to empty state
  11790. */
  11791. Engine.prototype.resetTextureCache = function () {
  11792. for (var key in this._boundTexturesCache) {
  11793. var boundTexture = this._boundTexturesCache[key];
  11794. if (boundTexture) {
  11795. this._removeDesignatedSlot(boundTexture);
  11796. }
  11797. this._boundTexturesCache[key] = null;
  11798. }
  11799. if (!this.disableTextureBindingOptimization) {
  11800. this._nextFreeTextureSlots = [];
  11801. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11802. this._nextFreeTextureSlots.push(slot);
  11803. }
  11804. }
  11805. this._currentTextureChannel = -1;
  11806. };
  11807. /**
  11808. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11809. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11810. * @returns true if engine is in deterministic lock step mode
  11811. */
  11812. Engine.prototype.isDeterministicLockStep = function () {
  11813. return this._deterministicLockstep;
  11814. };
  11815. /**
  11816. * Gets the max steps when engine is running in deterministic lock step
  11817. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11818. * @returns the max steps
  11819. */
  11820. Engine.prototype.getLockstepMaxSteps = function () {
  11821. return this._lockstepMaxSteps;
  11822. };
  11823. /**
  11824. * Gets an object containing information about the current webGL context
  11825. * @returns an object containing the vender, the renderer and the version of the current webGL context
  11826. */
  11827. Engine.prototype.getGlInfo = function () {
  11828. return {
  11829. vendor: this._glVendor,
  11830. renderer: this._glRenderer,
  11831. version: this._glVersion
  11832. };
  11833. };
  11834. /**
  11835. * Gets current aspect ratio
  11836. * @param camera defines the camera to use to get the aspect ratio
  11837. * @param useScreen defines if screen size must be used (or the current render target if any)
  11838. * @returns a number defining the aspect ratio
  11839. */
  11840. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11841. if (useScreen === void 0) { useScreen = false; }
  11842. var viewport = camera.viewport;
  11843. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11844. };
  11845. /**
  11846. * Gets the current render width
  11847. * @param useScreen defines if screen size must be used (or the current render target if any)
  11848. * @returns a number defining the current render width
  11849. */
  11850. Engine.prototype.getRenderWidth = function (useScreen) {
  11851. if (useScreen === void 0) { useScreen = false; }
  11852. if (!useScreen && this._currentRenderTarget) {
  11853. return this._currentRenderTarget.width;
  11854. }
  11855. return this._gl.drawingBufferWidth;
  11856. };
  11857. /**
  11858. * Gets the current render height
  11859. * @param useScreen defines if screen size must be used (or the current render target if any)
  11860. * @returns a number defining the current render height
  11861. */
  11862. Engine.prototype.getRenderHeight = function (useScreen) {
  11863. if (useScreen === void 0) { useScreen = false; }
  11864. if (!useScreen && this._currentRenderTarget) {
  11865. return this._currentRenderTarget.height;
  11866. }
  11867. return this._gl.drawingBufferHeight;
  11868. };
  11869. /**
  11870. * Gets the HTML canvas attached with the current webGL context
  11871. * @returns a HTML canvas
  11872. */
  11873. Engine.prototype.getRenderingCanvas = function () {
  11874. return this._renderingCanvas;
  11875. };
  11876. /**
  11877. * Gets the client rect of the HTML canvas attached with the current webGL context
  11878. * @returns a client rectanglee
  11879. */
  11880. Engine.prototype.getRenderingCanvasClientRect = function () {
  11881. if (!this._renderingCanvas) {
  11882. return null;
  11883. }
  11884. return this._renderingCanvas.getBoundingClientRect();
  11885. };
  11886. /**
  11887. * Defines the hardware scaling level.
  11888. * By default the hardware scaling level is computed from the window device ratio.
  11889. * 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.
  11890. * @param level defines the level to use
  11891. */
  11892. Engine.prototype.setHardwareScalingLevel = function (level) {
  11893. this._hardwareScalingLevel = level;
  11894. this.resize();
  11895. };
  11896. /**
  11897. * Gets the current hardware scaling level.
  11898. * By default the hardware scaling level is computed from the window device ratio.
  11899. * 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.
  11900. * @returns a number indicating the current hardware scaling level
  11901. */
  11902. Engine.prototype.getHardwareScalingLevel = function () {
  11903. return this._hardwareScalingLevel;
  11904. };
  11905. /**
  11906. * Gets the list of loaded textures
  11907. * @returns an array containing all loaded textures
  11908. */
  11909. Engine.prototype.getLoadedTexturesCache = function () {
  11910. return this._internalTexturesCache;
  11911. };
  11912. /**
  11913. * Gets the object containing all engine capabilities
  11914. * @returns the EngineCapabilities object
  11915. */
  11916. Engine.prototype.getCaps = function () {
  11917. return this._caps;
  11918. };
  11919. Object.defineProperty(Engine.prototype, "drawCalls", {
  11920. /** @ignore */
  11921. get: function () {
  11922. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11923. return 0;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11929. /** @ignore */
  11930. get: function () {
  11931. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11932. return null;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. /**
  11938. * Gets the current depth function
  11939. * @returns a number defining the depth function
  11940. */
  11941. Engine.prototype.getDepthFunction = function () {
  11942. return this._depthCullingState.depthFunc;
  11943. };
  11944. /**
  11945. * Sets the current depth function
  11946. * @param depthFunc defines the function to use
  11947. */
  11948. Engine.prototype.setDepthFunction = function (depthFunc) {
  11949. this._depthCullingState.depthFunc = depthFunc;
  11950. };
  11951. /**
  11952. * Sets the current depth function to GREATER
  11953. */
  11954. Engine.prototype.setDepthFunctionToGreater = function () {
  11955. this._depthCullingState.depthFunc = this._gl.GREATER;
  11956. };
  11957. /**
  11958. * Sets the current depth function to GEQUAL
  11959. */
  11960. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11961. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11962. };
  11963. /**
  11964. * Sets the current depth function to LESS
  11965. */
  11966. Engine.prototype.setDepthFunctionToLess = function () {
  11967. this._depthCullingState.depthFunc = this._gl.LESS;
  11968. };
  11969. /**
  11970. * Sets the current depth function to LEQUAL
  11971. */
  11972. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11973. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11974. };
  11975. /**
  11976. * Gets a boolean indicating if stencil buffer is enabled
  11977. * @returns the current stencil buffer state
  11978. */
  11979. Engine.prototype.getStencilBuffer = function () {
  11980. return this._stencilState.stencilTest;
  11981. };
  11982. /**
  11983. * Enable or disable the stencil buffer
  11984. * @param enable defines if the stencil buffer must be enabled or disabled
  11985. */
  11986. Engine.prototype.setStencilBuffer = function (enable) {
  11987. this._stencilState.stencilTest = enable;
  11988. };
  11989. /**
  11990. * Gets the current stencil mask
  11991. * @returns a number defining the new stencil mask to use
  11992. */
  11993. Engine.prototype.getStencilMask = function () {
  11994. return this._stencilState.stencilMask;
  11995. };
  11996. /**
  11997. * Sets the current stencil mask
  11998. * @param mask defines the new stencil mask to use
  11999. */
  12000. Engine.prototype.setStencilMask = function (mask) {
  12001. this._stencilState.stencilMask = mask;
  12002. };
  12003. /**
  12004. * Gets the current stencil function
  12005. * @returns a number defining the stencil function to use
  12006. */
  12007. Engine.prototype.getStencilFunction = function () {
  12008. return this._stencilState.stencilFunc;
  12009. };
  12010. /**
  12011. * Gets the current stencil reference value
  12012. * @returns a number defining the stencil reference value to use
  12013. */
  12014. Engine.prototype.getStencilFunctionReference = function () {
  12015. return this._stencilState.stencilFuncRef;
  12016. };
  12017. /**
  12018. * Gets the current stencil mask
  12019. * @returns a number defining the stencil mask to use
  12020. */
  12021. Engine.prototype.getStencilFunctionMask = function () {
  12022. return this._stencilState.stencilFuncMask;
  12023. };
  12024. /**
  12025. * Sets the current stencil function
  12026. * @param stencilFunc defines the new stencil function to use
  12027. */
  12028. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12029. this._stencilState.stencilFunc = stencilFunc;
  12030. };
  12031. /**
  12032. * Sets the current stencil reference
  12033. * @param reference defines the new stencil reference to use
  12034. */
  12035. Engine.prototype.setStencilFunctionReference = function (reference) {
  12036. this._stencilState.stencilFuncRef = reference;
  12037. };
  12038. /**
  12039. * Sets the current stencil mask
  12040. * @param mask defines the new stencil mask to use
  12041. */
  12042. Engine.prototype.setStencilFunctionMask = function (mask) {
  12043. this._stencilState.stencilFuncMask = mask;
  12044. };
  12045. /**
  12046. * Gets the current stencil operation when stencil fails
  12047. * @returns a number defining stencil operation to use when stencil fails
  12048. */
  12049. Engine.prototype.getStencilOperationFail = function () {
  12050. return this._stencilState.stencilOpStencilFail;
  12051. };
  12052. /**
  12053. * Gets the current stencil operation when depth fails
  12054. * @returns a number defining stencil operation to use when depth fails
  12055. */
  12056. Engine.prototype.getStencilOperationDepthFail = function () {
  12057. return this._stencilState.stencilOpDepthFail;
  12058. };
  12059. /**
  12060. * Gets the current stencil operation when stencil passes
  12061. * @returns a number defining stencil operation to use when stencil passes
  12062. */
  12063. Engine.prototype.getStencilOperationPass = function () {
  12064. return this._stencilState.stencilOpStencilDepthPass;
  12065. };
  12066. /**
  12067. * Sets the stencil operation to use when stencil fails
  12068. * @param operation defines the stencil operation to use when stencil fails
  12069. */
  12070. Engine.prototype.setStencilOperationFail = function (operation) {
  12071. this._stencilState.stencilOpStencilFail = operation;
  12072. };
  12073. /**
  12074. * Sets the stencil operation to use when depth fails
  12075. * @param operation defines the stencil operation to use when depth fails
  12076. */
  12077. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12078. this._stencilState.stencilOpDepthFail = operation;
  12079. };
  12080. /**
  12081. * Sets the stencil operation to use when stencil passes
  12082. * @param operation defines the stencil operation to use when stencil passes
  12083. */
  12084. Engine.prototype.setStencilOperationPass = function (operation) {
  12085. this._stencilState.stencilOpStencilDepthPass = operation;
  12086. };
  12087. /**
  12088. * Sets a boolean indicating if the dithering state is enabled or disabled
  12089. * @param value defines the dithering state
  12090. */
  12091. Engine.prototype.setDitheringState = function (value) {
  12092. if (value) {
  12093. this._gl.enable(this._gl.DITHER);
  12094. }
  12095. else {
  12096. this._gl.disable(this._gl.DITHER);
  12097. }
  12098. };
  12099. /**
  12100. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12101. * @param value defines the rasterizer state
  12102. */
  12103. Engine.prototype.setRasterizerState = function (value) {
  12104. if (value) {
  12105. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12106. }
  12107. else {
  12108. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12109. }
  12110. };
  12111. /**
  12112. * stop executing a render loop function and remove it from the execution array
  12113. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12114. */
  12115. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12116. if (!renderFunction) {
  12117. this._activeRenderLoops = [];
  12118. return;
  12119. }
  12120. var index = this._activeRenderLoops.indexOf(renderFunction);
  12121. if (index >= 0) {
  12122. this._activeRenderLoops.splice(index, 1);
  12123. }
  12124. };
  12125. /** @ignore */
  12126. Engine.prototype._renderLoop = function () {
  12127. if (!this._contextWasLost) {
  12128. var shouldRender = true;
  12129. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12130. shouldRender = false;
  12131. }
  12132. if (shouldRender) {
  12133. // Start new frame
  12134. this.beginFrame();
  12135. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12136. var renderFunction = this._activeRenderLoops[index];
  12137. renderFunction();
  12138. }
  12139. // Present
  12140. this.endFrame();
  12141. }
  12142. }
  12143. if (this._activeRenderLoops.length > 0) {
  12144. // Register new frame
  12145. var requester = null;
  12146. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12147. requester = this._vrDisplay;
  12148. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12149. }
  12150. else {
  12151. this._renderingQueueLaunched = false;
  12152. }
  12153. };
  12154. /**
  12155. * Register and execute a render loop. The engine can have more than one render function
  12156. * @param renderFunction defines the function to continuously execute
  12157. */
  12158. Engine.prototype.runRenderLoop = function (renderFunction) {
  12159. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12160. return;
  12161. }
  12162. this._activeRenderLoops.push(renderFunction);
  12163. if (!this._renderingQueueLaunched) {
  12164. this._renderingQueueLaunched = true;
  12165. this._bindedRenderFunction = this._renderLoop.bind(this);
  12166. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12167. }
  12168. };
  12169. /**
  12170. * Toggle full screen mode
  12171. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12172. * @param options defines an option object to be sent to the requestFullscreen function
  12173. */
  12174. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12175. if (this.isFullscreen) {
  12176. BABYLON.Tools.ExitFullscreen();
  12177. }
  12178. else {
  12179. this._pointerLockRequested = requestPointerLock;
  12180. if (this._renderingCanvas) {
  12181. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12182. }
  12183. }
  12184. };
  12185. /**
  12186. * Clear the current render buffer or the current render target (if any is set up)
  12187. * @param color defines the color to use
  12188. * @param backBuffer defines if the back buffer must be cleared
  12189. * @param depth defines if the depth buffer must be cleared
  12190. * @param stencil defines if the stencil buffer must be cleared
  12191. */
  12192. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12193. if (stencil === void 0) { stencil = false; }
  12194. this.applyStates();
  12195. var mode = 0;
  12196. if (backBuffer && color) {
  12197. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12198. mode |= this._gl.COLOR_BUFFER_BIT;
  12199. }
  12200. if (depth) {
  12201. this._gl.clearDepth(1.0);
  12202. mode |= this._gl.DEPTH_BUFFER_BIT;
  12203. }
  12204. if (stencil) {
  12205. this._gl.clearStencil(0);
  12206. mode |= this._gl.STENCIL_BUFFER_BIT;
  12207. }
  12208. this._gl.clear(mode);
  12209. };
  12210. /**
  12211. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12212. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12213. * @param y defines the y-coordinate of the corner of the clear rectangle
  12214. * @param width defines the width of the clear rectangle
  12215. * @param height defines the height of the clear rectangle
  12216. * @param clearColor defines the clear color
  12217. */
  12218. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12219. var gl = this._gl;
  12220. // Save state
  12221. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12222. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12223. // Change state
  12224. gl.enable(gl.SCISSOR_TEST);
  12225. gl.scissor(x, y, width, height);
  12226. // Clear
  12227. this.clear(clearColor, true, true, true);
  12228. // Restore state
  12229. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12230. if (curScissor === true) {
  12231. gl.enable(gl.SCISSOR_TEST);
  12232. }
  12233. else {
  12234. gl.disable(gl.SCISSOR_TEST);
  12235. }
  12236. };
  12237. /**
  12238. * Set the WebGL's viewport
  12239. * @param viewport defines the viewport element to be used
  12240. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12241. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12242. */
  12243. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12244. var width = requiredWidth || this.getRenderWidth();
  12245. var height = requiredHeight || this.getRenderHeight();
  12246. var x = viewport.x || 0;
  12247. var y = viewport.y || 0;
  12248. this._cachedViewport = viewport;
  12249. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12250. };
  12251. /**
  12252. * Directly set the WebGL Viewport
  12253. * @param x defines the x coordinate of the viewport (in screen space)
  12254. * @param y defines the y coordinate of the viewport (in screen space)
  12255. * @param width defines the width of the viewport (in screen space)
  12256. * @param height defines the height of the viewport (in screen space)
  12257. * @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
  12258. */
  12259. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12260. var currentViewport = this._cachedViewport;
  12261. this._cachedViewport = null;
  12262. this._gl.viewport(x, y, width, height);
  12263. return currentViewport;
  12264. };
  12265. /**
  12266. * Begin a new frame
  12267. */
  12268. Engine.prototype.beginFrame = function () {
  12269. this.onBeginFrameObservable.notifyObservers(this);
  12270. this._measureFps();
  12271. };
  12272. /**
  12273. * Enf the current frame
  12274. */
  12275. Engine.prototype.endFrame = function () {
  12276. // Force a flush in case we are using a bad OS.
  12277. if (this._badOS) {
  12278. this.flushFramebuffer();
  12279. }
  12280. // Submit frame to the vr device, if enabled
  12281. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12282. // TODO: We should only submit the frame if we read frameData successfully.
  12283. this._vrDisplay.submitFrame();
  12284. }
  12285. this.onEndFrameObservable.notifyObservers(this);
  12286. };
  12287. /**
  12288. * Resize the view according to the canvas' size
  12289. */
  12290. Engine.prototype.resize = function () {
  12291. // We're not resizing the size of the canvas while in VR mode & presenting
  12292. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12293. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12294. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12295. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12296. }
  12297. };
  12298. /**
  12299. * Force a specific size of the canvas
  12300. * @param width defines the new canvas' width
  12301. * @param height defines the new canvas' height
  12302. */
  12303. Engine.prototype.setSize = function (width, height) {
  12304. if (!this._renderingCanvas) {
  12305. return;
  12306. }
  12307. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12308. return;
  12309. }
  12310. this._renderingCanvas.width = width;
  12311. this._renderingCanvas.height = height;
  12312. for (var index = 0; index < this.scenes.length; index++) {
  12313. var scene = this.scenes[index];
  12314. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12315. var cam = scene.cameras[camIndex];
  12316. cam._currentRenderId = 0;
  12317. }
  12318. }
  12319. if (this.onResizeObservable.hasObservers) {
  12320. this.onResizeObservable.notifyObservers(this);
  12321. }
  12322. };
  12323. // WebVR functions
  12324. /**
  12325. * Gets a boolean indicating if a webVR device was detected
  12326. * @returns true if a webVR device was detected
  12327. */
  12328. Engine.prototype.isVRDevicePresent = function () {
  12329. return !!this._vrDisplay;
  12330. };
  12331. /**
  12332. * Gets the current webVR device
  12333. * @returns the current webVR device (or null)
  12334. */
  12335. Engine.prototype.getVRDevice = function () {
  12336. return this._vrDisplay;
  12337. };
  12338. /**
  12339. * Initializes a webVR display and starts listening to display change events
  12340. * The onVRDisplayChangedObservable will be notified upon these changes
  12341. * @returns The onVRDisplayChangedObservable
  12342. */
  12343. Engine.prototype.initWebVR = function () {
  12344. this.initWebVRAsync();
  12345. return this.onVRDisplayChangedObservable;
  12346. };
  12347. /**
  12348. * Initializes a webVR display and starts listening to display change events
  12349. * The onVRDisplayChangedObservable will be notified upon these changes
  12350. * @returns A promise containing a VRDisplay and if vr is supported
  12351. */
  12352. Engine.prototype.initWebVRAsync = function () {
  12353. var _this = this;
  12354. var notifyObservers = function () {
  12355. var eventArgs = {
  12356. vrDisplay: _this._vrDisplay,
  12357. vrSupported: _this._vrSupported
  12358. };
  12359. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12360. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12361. };
  12362. if (!this._onVrDisplayConnect) {
  12363. this._onVrDisplayConnect = function (event) {
  12364. _this._vrDisplay = event.display;
  12365. notifyObservers();
  12366. };
  12367. this._onVrDisplayDisconnect = function () {
  12368. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12369. _this._vrDisplay = undefined;
  12370. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12371. notifyObservers();
  12372. };
  12373. this._onVrDisplayPresentChange = function () {
  12374. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12375. };
  12376. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12377. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12378. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12379. }
  12380. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12381. this._webVRInitPromise.then(notifyObservers);
  12382. return this._webVRInitPromise;
  12383. };
  12384. /**
  12385. * Call this function to switch to webVR mode
  12386. * Will do nothing if webVR is not supported or if there is no webVR device
  12387. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12388. */
  12389. Engine.prototype.enableVR = function () {
  12390. var _this = this;
  12391. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12392. var onResolved = function () {
  12393. _this.onVRRequestPresentComplete.notifyObservers(true);
  12394. _this._onVRFullScreenTriggered();
  12395. };
  12396. var onRejected = function () {
  12397. _this.onVRRequestPresentComplete.notifyObservers(false);
  12398. };
  12399. this.onVRRequestPresentStart.notifyObservers(this);
  12400. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12401. }
  12402. };
  12403. /**
  12404. * Call this function to leave webVR mode
  12405. * Will do nothing if webVR is not supported or if there is no webVR device
  12406. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12407. */
  12408. Engine.prototype.disableVR = function () {
  12409. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12410. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12411. }
  12412. };
  12413. Engine.prototype._getVRDisplaysAsync = function () {
  12414. var _this = this;
  12415. return new Promise(function (res, rej) {
  12416. if (navigator.getVRDisplays) {
  12417. navigator.getVRDisplays().then(function (devices) {
  12418. _this._vrSupported = true;
  12419. // note that devices may actually be an empty array. This is fine;
  12420. // we expect this._vrDisplay to be undefined in this case.
  12421. _this._vrDisplay = devices[0];
  12422. res({
  12423. vrDisplay: _this._vrDisplay,
  12424. vrSupported: _this._vrSupported
  12425. });
  12426. });
  12427. }
  12428. else {
  12429. _this._vrDisplay = undefined;
  12430. _this._vrSupported = false;
  12431. res({
  12432. vrDisplay: _this._vrDisplay,
  12433. vrSupported: _this._vrSupported
  12434. });
  12435. }
  12436. });
  12437. };
  12438. /**
  12439. * Binds the frame buffer to the specified texture.
  12440. * @param texture The texture to render to or null for the default canvas
  12441. * @param faceIndex The face of the texture to render to in case of cube texture
  12442. * @param requiredWidth The width of the target to render to
  12443. * @param requiredHeight The height of the target to render to
  12444. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12445. * @param depthStencilTexture The depth stencil texture to use to render
  12446. */
  12447. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12448. if (this._currentRenderTarget) {
  12449. this.unBindFramebuffer(this._currentRenderTarget);
  12450. }
  12451. this._currentRenderTarget = texture;
  12452. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12453. var gl = this._gl;
  12454. if (texture.isCube) {
  12455. if (faceIndex === undefined) {
  12456. faceIndex = 0;
  12457. }
  12458. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12459. if (depthStencilTexture) {
  12460. if (depthStencilTexture._generateStencilBuffer) {
  12461. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12462. }
  12463. else {
  12464. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12465. }
  12466. }
  12467. }
  12468. if (this._cachedViewport && !forceFullscreenViewport) {
  12469. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12470. }
  12471. else {
  12472. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12473. }
  12474. this.wipeCaches();
  12475. };
  12476. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12477. if (this._currentFramebuffer !== framebuffer) {
  12478. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12479. this._currentFramebuffer = framebuffer;
  12480. }
  12481. };
  12482. /**
  12483. * Unbind the current render target texture from the webGL context
  12484. * @param texture defines the render target texture to unbind
  12485. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12486. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12487. */
  12488. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12489. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12490. this._currentRenderTarget = null;
  12491. // If MSAA, we need to bitblt back to main texture
  12492. var gl = this._gl;
  12493. if (texture._MSAAFramebuffer) {
  12494. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12495. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12496. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12497. }
  12498. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12499. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12500. gl.generateMipmap(gl.TEXTURE_2D);
  12501. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12502. }
  12503. if (onBeforeUnbind) {
  12504. if (texture._MSAAFramebuffer) {
  12505. // Bind the correct framebuffer
  12506. this.bindUnboundFramebuffer(texture._framebuffer);
  12507. }
  12508. onBeforeUnbind();
  12509. }
  12510. this.bindUnboundFramebuffer(null);
  12511. };
  12512. /**
  12513. * Unbind a list of render target textures from the webGL context
  12514. * This is used only when drawBuffer extension or webGL2 are active
  12515. * @param textures defines the render target textures to unbind
  12516. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12517. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12518. */
  12519. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12520. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12521. this._currentRenderTarget = null;
  12522. // If MSAA, we need to bitblt back to main texture
  12523. var gl = this._gl;
  12524. if (textures[0]._MSAAFramebuffer) {
  12525. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12526. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12527. var attachments = textures[0]._attachments;
  12528. if (!attachments) {
  12529. attachments = new Array(textures.length);
  12530. textures[0]._attachments = attachments;
  12531. }
  12532. for (var i = 0; i < textures.length; i++) {
  12533. var texture = textures[i];
  12534. for (var j = 0; j < attachments.length; j++) {
  12535. attachments[j] = gl.NONE;
  12536. }
  12537. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12538. gl.readBuffer(attachments[i]);
  12539. gl.drawBuffers(attachments);
  12540. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12541. }
  12542. for (var i = 0; i < attachments.length; i++) {
  12543. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12544. }
  12545. gl.drawBuffers(attachments);
  12546. }
  12547. for (var i = 0; i < textures.length; i++) {
  12548. var texture = textures[i];
  12549. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12550. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12551. gl.generateMipmap(gl.TEXTURE_2D);
  12552. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12553. }
  12554. }
  12555. if (onBeforeUnbind) {
  12556. if (textures[0]._MSAAFramebuffer) {
  12557. // Bind the correct framebuffer
  12558. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12559. }
  12560. onBeforeUnbind();
  12561. }
  12562. this.bindUnboundFramebuffer(null);
  12563. };
  12564. /**
  12565. * Force the mipmap generation for the given render target texture
  12566. * @param texture defines the render target texture to use
  12567. */
  12568. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12569. if (texture.generateMipMaps) {
  12570. var gl = this._gl;
  12571. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12572. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12573. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12574. }
  12575. };
  12576. /**
  12577. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12578. */
  12579. Engine.prototype.flushFramebuffer = function () {
  12580. this._gl.flush();
  12581. };
  12582. /**
  12583. * Unbind the current render target and bind the default framebuffer
  12584. */
  12585. Engine.prototype.restoreDefaultFramebuffer = function () {
  12586. if (this._currentRenderTarget) {
  12587. this.unBindFramebuffer(this._currentRenderTarget);
  12588. }
  12589. else {
  12590. this.bindUnboundFramebuffer(null);
  12591. }
  12592. if (this._cachedViewport) {
  12593. this.setViewport(this._cachedViewport);
  12594. }
  12595. this.wipeCaches();
  12596. };
  12597. // UBOs
  12598. /**
  12599. * Create an uniform buffer
  12600. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12601. * @param elements defines the content of the uniform buffer
  12602. * @returns the webGL uniform buffer
  12603. */
  12604. Engine.prototype.createUniformBuffer = function (elements) {
  12605. var ubo = this._gl.createBuffer();
  12606. if (!ubo) {
  12607. throw new Error("Unable to create uniform buffer");
  12608. }
  12609. this.bindUniformBuffer(ubo);
  12610. if (elements instanceof Float32Array) {
  12611. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12612. }
  12613. else {
  12614. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12615. }
  12616. this.bindUniformBuffer(null);
  12617. ubo.references = 1;
  12618. return ubo;
  12619. };
  12620. /**
  12621. * Create a dynamic uniform buffer
  12622. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12623. * @param elements defines the content of the uniform buffer
  12624. * @returns the webGL uniform buffer
  12625. */
  12626. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12627. var ubo = this._gl.createBuffer();
  12628. if (!ubo) {
  12629. throw new Error("Unable to create dynamic uniform buffer");
  12630. }
  12631. this.bindUniformBuffer(ubo);
  12632. if (elements instanceof Float32Array) {
  12633. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12634. }
  12635. else {
  12636. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12637. }
  12638. this.bindUniformBuffer(null);
  12639. ubo.references = 1;
  12640. return ubo;
  12641. };
  12642. /**
  12643. * Update an existing uniform buffer
  12644. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12645. * @param uniformBuffer defines the target uniform buffer
  12646. * @param elements defines the content to update
  12647. * @param offset defines the offset in the uniform buffer where update should start
  12648. * @param count defines the size of the data to update
  12649. */
  12650. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12651. this.bindUniformBuffer(uniformBuffer);
  12652. if (offset === undefined) {
  12653. offset = 0;
  12654. }
  12655. if (count === undefined) {
  12656. if (elements instanceof Float32Array) {
  12657. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12658. }
  12659. else {
  12660. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12661. }
  12662. }
  12663. else {
  12664. if (elements instanceof Float32Array) {
  12665. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12666. }
  12667. else {
  12668. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12669. }
  12670. }
  12671. this.bindUniformBuffer(null);
  12672. };
  12673. // VBOs
  12674. Engine.prototype._resetVertexBufferBinding = function () {
  12675. this.bindArrayBuffer(null);
  12676. this._cachedVertexBuffers = null;
  12677. };
  12678. /**
  12679. * Creates a vertex buffer
  12680. * @param data the data for the vertex buffer
  12681. * @returns the new WebGL static buffer
  12682. */
  12683. Engine.prototype.createVertexBuffer = function (data) {
  12684. var vbo = this._gl.createBuffer();
  12685. if (!vbo) {
  12686. throw new Error("Unable to create vertex buffer");
  12687. }
  12688. this.bindArrayBuffer(vbo);
  12689. if (data instanceof Array) {
  12690. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12691. }
  12692. else {
  12693. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12694. }
  12695. this._resetVertexBufferBinding();
  12696. vbo.references = 1;
  12697. return vbo;
  12698. };
  12699. /**
  12700. * Creates a dynamic vertex buffer
  12701. * @param data the data for the dynamic vertex buffer
  12702. * @returns the new WebGL dynamic buffer
  12703. */
  12704. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12705. var vbo = this._gl.createBuffer();
  12706. if (!vbo) {
  12707. throw new Error("Unable to create dynamic vertex buffer");
  12708. }
  12709. this.bindArrayBuffer(vbo);
  12710. if (data instanceof Array) {
  12711. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12712. }
  12713. else {
  12714. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12715. }
  12716. this._resetVertexBufferBinding();
  12717. vbo.references = 1;
  12718. return vbo;
  12719. };
  12720. /**
  12721. * Update a dynamic index buffer
  12722. * @param indexBuffer defines the target index buffer
  12723. * @param indices defines the data to update
  12724. * @param offset defines the offset in the target index buffer where update should start
  12725. */
  12726. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12727. if (offset === void 0) { offset = 0; }
  12728. // Force cache update
  12729. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12730. this.bindIndexBuffer(indexBuffer);
  12731. var arrayBuffer;
  12732. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12733. arrayBuffer = indices;
  12734. }
  12735. else {
  12736. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12737. }
  12738. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12739. this._resetIndexBufferBinding();
  12740. };
  12741. /**
  12742. * Updates a dynamic vertex buffer.
  12743. * @param vertexBuffer the vertex buffer to update
  12744. * @param data the data used to update the vertex buffer
  12745. * @param byteOffset the byte offset of the data
  12746. * @param byteLength the byte length of the data
  12747. */
  12748. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12749. this.bindArrayBuffer(vertexBuffer);
  12750. if (byteOffset === undefined) {
  12751. byteOffset = 0;
  12752. }
  12753. if (byteLength === undefined) {
  12754. if (data instanceof Array) {
  12755. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12756. }
  12757. else {
  12758. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12759. }
  12760. }
  12761. else {
  12762. if (data instanceof Array) {
  12763. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12764. }
  12765. else {
  12766. if (data instanceof ArrayBuffer) {
  12767. data = new Uint8Array(data, byteOffset, byteLength);
  12768. }
  12769. else {
  12770. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12771. }
  12772. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12773. }
  12774. }
  12775. this._resetVertexBufferBinding();
  12776. };
  12777. Engine.prototype._resetIndexBufferBinding = function () {
  12778. this.bindIndexBuffer(null);
  12779. this._cachedIndexBuffer = null;
  12780. };
  12781. /**
  12782. * Creates a new index buffer
  12783. * @param indices defines the content of the index buffer
  12784. * @param updatable defines if the index buffer must be updatable
  12785. * @returns a new webGL buffer
  12786. */
  12787. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12788. var vbo = this._gl.createBuffer();
  12789. if (!vbo) {
  12790. throw new Error("Unable to create index buffer");
  12791. }
  12792. this.bindIndexBuffer(vbo);
  12793. // Check for 32 bits indices
  12794. var arrayBuffer;
  12795. var need32Bits = false;
  12796. if (indices instanceof Uint16Array) {
  12797. arrayBuffer = indices;
  12798. }
  12799. else {
  12800. //check 32 bit support
  12801. if (this._caps.uintIndices) {
  12802. if (indices instanceof Uint32Array) {
  12803. arrayBuffer = indices;
  12804. need32Bits = true;
  12805. }
  12806. else {
  12807. //number[] or Int32Array, check if 32 bit is necessary
  12808. for (var index = 0; index < indices.length; index++) {
  12809. if (indices[index] > 65535) {
  12810. need32Bits = true;
  12811. break;
  12812. }
  12813. }
  12814. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12815. }
  12816. }
  12817. else {
  12818. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12819. arrayBuffer = new Uint16Array(indices);
  12820. }
  12821. }
  12822. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12823. this._resetIndexBufferBinding();
  12824. vbo.references = 1;
  12825. vbo.is32Bits = need32Bits;
  12826. return vbo;
  12827. };
  12828. /**
  12829. * Bind a webGL buffer to the webGL context
  12830. * @param buffer defines the buffer to bind
  12831. */
  12832. Engine.prototype.bindArrayBuffer = function (buffer) {
  12833. if (!this._vaoRecordInProgress) {
  12834. this._unbindVertexArrayObject();
  12835. }
  12836. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12837. };
  12838. /**
  12839. * Bind an uniform buffer to the current webGL context
  12840. * @param buffer defines the buffer to bind
  12841. */
  12842. Engine.prototype.bindUniformBuffer = function (buffer) {
  12843. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12844. };
  12845. /**
  12846. * Bind a buffer to the current webGL context at a given location
  12847. * @param buffer defines the buffer to bind
  12848. * @param location defines the index where to bind the buffer
  12849. */
  12850. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12851. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12852. };
  12853. /**
  12854. * Bind a specific block at a given index in a specific shader program
  12855. * @param shaderProgram defines the shader program
  12856. * @param blockName defines the block name
  12857. * @param index defines the index where to bind the block
  12858. */
  12859. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12860. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12861. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12862. };
  12863. ;
  12864. Engine.prototype.bindIndexBuffer = function (buffer) {
  12865. if (!this._vaoRecordInProgress) {
  12866. this._unbindVertexArrayObject();
  12867. }
  12868. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12869. };
  12870. Engine.prototype.bindBuffer = function (buffer, target) {
  12871. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12872. this._gl.bindBuffer(target, buffer);
  12873. this._currentBoundBuffer[target] = buffer;
  12874. }
  12875. };
  12876. /**
  12877. * update the bound buffer with the given data
  12878. * @param data defines the data to update
  12879. */
  12880. Engine.prototype.updateArrayBuffer = function (data) {
  12881. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12882. };
  12883. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12884. var pointer = this._currentBufferPointers[indx];
  12885. var changed = false;
  12886. if (!pointer.active) {
  12887. changed = true;
  12888. pointer.active = true;
  12889. pointer.index = indx;
  12890. pointer.size = size;
  12891. pointer.type = type;
  12892. pointer.normalized = normalized;
  12893. pointer.stride = stride;
  12894. pointer.offset = offset;
  12895. pointer.buffer = buffer;
  12896. }
  12897. else {
  12898. if (pointer.buffer !== buffer) {
  12899. pointer.buffer = buffer;
  12900. changed = true;
  12901. }
  12902. if (pointer.size !== size) {
  12903. pointer.size = size;
  12904. changed = true;
  12905. }
  12906. if (pointer.type !== type) {
  12907. pointer.type = type;
  12908. changed = true;
  12909. }
  12910. if (pointer.normalized !== normalized) {
  12911. pointer.normalized = normalized;
  12912. changed = true;
  12913. }
  12914. if (pointer.stride !== stride) {
  12915. pointer.stride = stride;
  12916. changed = true;
  12917. }
  12918. if (pointer.offset !== offset) {
  12919. pointer.offset = offset;
  12920. changed = true;
  12921. }
  12922. }
  12923. if (changed || this._vaoRecordInProgress) {
  12924. this.bindArrayBuffer(buffer);
  12925. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12926. }
  12927. };
  12928. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12929. if (indexBuffer == null) {
  12930. return;
  12931. }
  12932. if (this._cachedIndexBuffer !== indexBuffer) {
  12933. this._cachedIndexBuffer = indexBuffer;
  12934. this.bindIndexBuffer(indexBuffer);
  12935. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12936. }
  12937. };
  12938. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12939. var attributes = effect.getAttributesNames();
  12940. if (!this._vaoRecordInProgress) {
  12941. this._unbindVertexArrayObject();
  12942. }
  12943. this.unbindAllAttributes();
  12944. for (var index = 0; index < attributes.length; index++) {
  12945. var order = effect.getAttributeLocation(index);
  12946. if (order >= 0) {
  12947. var vertexBuffer = vertexBuffers[attributes[index]];
  12948. if (!vertexBuffer) {
  12949. continue;
  12950. }
  12951. this._gl.enableVertexAttribArray(order);
  12952. if (!this._vaoRecordInProgress) {
  12953. this._vertexAttribArraysEnabled[order] = true;
  12954. }
  12955. var buffer = vertexBuffer.getBuffer();
  12956. if (buffer) {
  12957. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  12958. if (vertexBuffer.getIsInstanced()) {
  12959. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12960. if (!this._vaoRecordInProgress) {
  12961. this._currentInstanceLocations.push(order);
  12962. this._currentInstanceBuffers.push(buffer);
  12963. }
  12964. }
  12965. }
  12966. }
  12967. }
  12968. };
  12969. /**
  12970. * Records a vertex array object
  12971. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  12972. * @param vertexBuffers defines the list of vertex buffers to store
  12973. * @param indexBuffer defines the index buffer to store
  12974. * @param effect defines the effect to store
  12975. * @returns the new vertex array object
  12976. */
  12977. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12978. var vao = this._gl.createVertexArray();
  12979. this._vaoRecordInProgress = true;
  12980. this._gl.bindVertexArray(vao);
  12981. this._mustWipeVertexAttributes = true;
  12982. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12983. this.bindIndexBuffer(indexBuffer);
  12984. this._vaoRecordInProgress = false;
  12985. this._gl.bindVertexArray(null);
  12986. return vao;
  12987. };
  12988. /**
  12989. * Bind a specific vertex array object
  12990. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  12991. * @param vertexArrayObject defines the vertex array object to bind
  12992. * @param indexBuffer defines the index buffer to bind
  12993. */
  12994. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12995. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12996. this._cachedVertexArrayObject = vertexArrayObject;
  12997. this._gl.bindVertexArray(vertexArrayObject);
  12998. this._cachedVertexBuffers = null;
  12999. this._cachedIndexBuffer = null;
  13000. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13001. this._mustWipeVertexAttributes = true;
  13002. }
  13003. };
  13004. /**
  13005. * Bind webGl buffers directly to the webGL context
  13006. * @param vertexBuffer defines the vertex buffer to bind
  13007. * @param indexBuffer defines the index buffer to bind
  13008. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13009. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13010. * @param effect defines the effect associated with the vertex buffer
  13011. */
  13012. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13013. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13014. this._cachedVertexBuffers = vertexBuffer;
  13015. this._cachedEffectForVertexBuffers = effect;
  13016. var attributesCount = effect.getAttributesCount();
  13017. this._unbindVertexArrayObject();
  13018. this.unbindAllAttributes();
  13019. var offset = 0;
  13020. for (var index = 0; index < attributesCount; index++) {
  13021. if (index < vertexDeclaration.length) {
  13022. var order = effect.getAttributeLocation(index);
  13023. if (order >= 0) {
  13024. this._gl.enableVertexAttribArray(order);
  13025. this._vertexAttribArraysEnabled[order] = true;
  13026. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13027. }
  13028. offset += vertexDeclaration[index] * 4;
  13029. }
  13030. }
  13031. }
  13032. this._bindIndexBufferWithCache(indexBuffer);
  13033. };
  13034. Engine.prototype._unbindVertexArrayObject = function () {
  13035. if (!this._cachedVertexArrayObject) {
  13036. return;
  13037. }
  13038. this._cachedVertexArrayObject = null;
  13039. this._gl.bindVertexArray(null);
  13040. };
  13041. /**
  13042. * Bind a list of vertex buffers to the webGL context
  13043. * @param vertexBuffers defines the list of vertex buffers to bind
  13044. * @param indexBuffer defines the index buffer to bind
  13045. * @param effect defines the effect associated with the vertex buffers
  13046. */
  13047. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13048. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13049. this._cachedVertexBuffers = vertexBuffers;
  13050. this._cachedEffectForVertexBuffers = effect;
  13051. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13052. }
  13053. this._bindIndexBufferWithCache(indexBuffer);
  13054. };
  13055. /**
  13056. * Unbind all instance attributes
  13057. */
  13058. Engine.prototype.unbindInstanceAttributes = function () {
  13059. var boundBuffer;
  13060. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13061. var instancesBuffer = this._currentInstanceBuffers[i];
  13062. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13063. boundBuffer = instancesBuffer;
  13064. this.bindArrayBuffer(instancesBuffer);
  13065. }
  13066. var offsetLocation = this._currentInstanceLocations[i];
  13067. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13068. }
  13069. this._currentInstanceBuffers.length = 0;
  13070. this._currentInstanceLocations.length = 0;
  13071. };
  13072. /**
  13073. * Release and free the memory of a vertex array object
  13074. * @param vao defines the vertex array object to delete
  13075. */
  13076. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13077. this._gl.deleteVertexArray(vao);
  13078. };
  13079. /** @ignore */
  13080. Engine.prototype._releaseBuffer = function (buffer) {
  13081. buffer.references--;
  13082. if (buffer.references === 0) {
  13083. this._gl.deleteBuffer(buffer);
  13084. return true;
  13085. }
  13086. return false;
  13087. };
  13088. /**
  13089. * Creates a webGL buffer to use with instanciation
  13090. * @param capacity defines the size of the buffer
  13091. * @returns the webGL buffer
  13092. */
  13093. Engine.prototype.createInstancesBuffer = function (capacity) {
  13094. var buffer = this._gl.createBuffer();
  13095. if (!buffer) {
  13096. throw new Error("Unable to create instance buffer");
  13097. }
  13098. buffer.capacity = capacity;
  13099. this.bindArrayBuffer(buffer);
  13100. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13101. return buffer;
  13102. };
  13103. /**
  13104. * Delete a webGL buffer used with instanciation
  13105. * @param buffer defines the webGL buffer to delete
  13106. */
  13107. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13108. this._gl.deleteBuffer(buffer);
  13109. };
  13110. /**
  13111. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13112. * @param instancesBuffer defines the webGL buffer to update and bind
  13113. * @param data defines the data to store in the buffer
  13114. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13115. */
  13116. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13117. this.bindArrayBuffer(instancesBuffer);
  13118. if (data) {
  13119. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13120. }
  13121. if (offsetLocations[0].index !== undefined) {
  13122. var stride = 0;
  13123. for (var i = 0; i < offsetLocations.length; i++) {
  13124. var ai = offsetLocations[i];
  13125. stride += ai.attributeSize * 4;
  13126. }
  13127. for (var i = 0; i < offsetLocations.length; i++) {
  13128. var ai = offsetLocations[i];
  13129. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13130. this._gl.enableVertexAttribArray(ai.index);
  13131. this._vertexAttribArraysEnabled[ai.index] = true;
  13132. }
  13133. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13134. this._gl.vertexAttribDivisor(ai.index, 1);
  13135. this._currentInstanceLocations.push(ai.index);
  13136. this._currentInstanceBuffers.push(instancesBuffer);
  13137. }
  13138. }
  13139. else {
  13140. for (var index = 0; index < 4; index++) {
  13141. var offsetLocation = offsetLocations[index];
  13142. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13143. this._gl.enableVertexAttribArray(offsetLocation);
  13144. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13145. }
  13146. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13147. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13148. this._currentInstanceLocations.push(offsetLocation);
  13149. this._currentInstanceBuffers.push(instancesBuffer);
  13150. }
  13151. }
  13152. };
  13153. /**
  13154. * Apply all cached states (depth, culling, stencil and alpha)
  13155. */
  13156. Engine.prototype.applyStates = function () {
  13157. this._depthCullingState.apply(this._gl);
  13158. this._stencilState.apply(this._gl);
  13159. this._alphaState.apply(this._gl);
  13160. };
  13161. /**
  13162. * Send a draw order
  13163. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13164. * @param indexStart defines the starting index
  13165. * @param indexCount defines the number of index to draw
  13166. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13167. */
  13168. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13169. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13170. };
  13171. /**
  13172. * Draw a list of points
  13173. * @param verticesStart defines the index of first vertex to draw
  13174. * @param verticesCount defines the count of vertices to draw
  13175. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13176. */
  13177. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13178. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13179. };
  13180. /**
  13181. * Draw a list of unindexed primitives
  13182. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13183. * @param verticesStart defines the index of first vertex to draw
  13184. * @param verticesCount defines the count of vertices to draw
  13185. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13186. */
  13187. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13188. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13189. };
  13190. /**
  13191. * Draw a list of indexed primitives
  13192. * @param fillMode defines the primitive to use
  13193. * @param indexStart defines the starting index
  13194. * @param indexCount defines the number of index to draw
  13195. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13196. */
  13197. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13198. // Apply states
  13199. this.applyStates();
  13200. this._drawCalls.addCount(1, false);
  13201. // Render
  13202. var drawMode = this._drawMode(fillMode);
  13203. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13204. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13205. if (instancesCount) {
  13206. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13207. }
  13208. else {
  13209. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13210. }
  13211. };
  13212. /**
  13213. * Draw a list of unindexed primitives
  13214. * @param fillMode defines the primitive to use
  13215. * @param verticesStart defines the index of first vertex to draw
  13216. * @param verticesCount defines the count of vertices to draw
  13217. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13218. */
  13219. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13220. // Apply states
  13221. this.applyStates();
  13222. this._drawCalls.addCount(1, false);
  13223. var drawMode = this._drawMode(fillMode);
  13224. if (instancesCount) {
  13225. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13226. }
  13227. else {
  13228. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13229. }
  13230. };
  13231. Engine.prototype._drawMode = function (fillMode) {
  13232. switch (fillMode) {
  13233. // Triangle views
  13234. case BABYLON.Material.TriangleFillMode:
  13235. return this._gl.TRIANGLES;
  13236. case BABYLON.Material.PointFillMode:
  13237. return this._gl.POINTS;
  13238. case BABYLON.Material.WireFrameFillMode:
  13239. return this._gl.LINES;
  13240. // Draw modes
  13241. case BABYLON.Material.PointListDrawMode:
  13242. return this._gl.POINTS;
  13243. case BABYLON.Material.LineListDrawMode:
  13244. return this._gl.LINES;
  13245. case BABYLON.Material.LineLoopDrawMode:
  13246. return this._gl.LINE_LOOP;
  13247. case BABYLON.Material.LineStripDrawMode:
  13248. return this._gl.LINE_STRIP;
  13249. case BABYLON.Material.TriangleStripDrawMode:
  13250. return this._gl.TRIANGLE_STRIP;
  13251. case BABYLON.Material.TriangleFanDrawMode:
  13252. return this._gl.TRIANGLE_FAN;
  13253. default:
  13254. return this._gl.TRIANGLES;
  13255. }
  13256. };
  13257. // Shaders
  13258. /** @ignore */
  13259. Engine.prototype._releaseEffect = function (effect) {
  13260. if (this._compiledEffects[effect._key]) {
  13261. delete this._compiledEffects[effect._key];
  13262. this._deleteProgram(effect.getProgram());
  13263. }
  13264. };
  13265. /** @ignore */
  13266. Engine.prototype._deleteProgram = function (program) {
  13267. if (program) {
  13268. program.__SPECTOR_rebuildProgram = null;
  13269. if (program.transformFeedback) {
  13270. this.deleteTransformFeedback(program.transformFeedback);
  13271. program.transformFeedback = null;
  13272. }
  13273. this._gl.deleteProgram(program);
  13274. }
  13275. };
  13276. /**
  13277. * Create a new effect (used to store vertex/fragment shaders)
  13278. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13279. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13280. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13281. * @param samplers defines an array of string used to represent textures
  13282. * @param defines defines the string containing the defines to use to compile the shaders
  13283. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13284. * @param onCompiled defines a function to call when the effect creation is successful
  13285. * @param onError defines a function to call when the effect creation has failed
  13286. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13287. * @returns the new Effect
  13288. */
  13289. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13290. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13291. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13292. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13293. if (this._compiledEffects[name]) {
  13294. var compiledEffect = this._compiledEffects[name];
  13295. if (onCompiled && compiledEffect.isReady()) {
  13296. onCompiled(compiledEffect);
  13297. }
  13298. return compiledEffect;
  13299. }
  13300. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13301. effect._key = name;
  13302. this._compiledEffects[name] = effect;
  13303. return effect;
  13304. };
  13305. /**
  13306. * Create an effect to use with particle systems
  13307. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13308. * @param uniformsNames defines a list of attribute names
  13309. * @param samplers defines an array of string used to represent textures
  13310. * @param defines defines the string containing the defines to use to compile the shaders
  13311. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13312. * @param onCompiled defines a function to call when the effect creation is successful
  13313. * @param onError defines a function to call when the effect creation has failed
  13314. * @returns the new Effect
  13315. */
  13316. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13317. if (uniformsNames === void 0) { uniformsNames = []; }
  13318. if (samplers === void 0) { samplers = []; }
  13319. if (defines === void 0) { defines = ""; }
  13320. return this.createEffect({
  13321. vertex: "particles",
  13322. fragmentElement: fragmentName
  13323. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13324. };
  13325. /**
  13326. * Directly creates a webGL program
  13327. * @param vertexCode defines the vertex shader code to use
  13328. * @param fragmentCode defines the fragment shader code to use
  13329. * @param context defines the webGL context to use (if not set, the current one will be used)
  13330. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13331. * @returns the new webGL program
  13332. */
  13333. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13334. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13335. context = context || this._gl;
  13336. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13337. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13338. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13339. };
  13340. /**
  13341. * Creates a webGL program
  13342. * @param vertexCode defines the vertex shader code to use
  13343. * @param fragmentCode defines the fragment shader code to use
  13344. * @param defines defines the string containing the defines to use to compile the shaders
  13345. * @param context defines the webGL context to use (if not set, the current one will be used)
  13346. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13347. * @returns the new webGL program
  13348. */
  13349. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13350. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13351. context = context || this._gl;
  13352. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13353. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13354. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13355. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13356. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13357. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13358. return program;
  13359. };
  13360. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13361. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13362. var shaderProgram = context.createProgram();
  13363. if (!shaderProgram) {
  13364. throw new Error("Unable to create program");
  13365. }
  13366. context.attachShader(shaderProgram, vertexShader);
  13367. context.attachShader(shaderProgram, fragmentShader);
  13368. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13369. var transformFeedback = this.createTransformFeedback();
  13370. this.bindTransformFeedback(transformFeedback);
  13371. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13372. shaderProgram.transformFeedback = transformFeedback;
  13373. }
  13374. context.linkProgram(shaderProgram);
  13375. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13376. this.bindTransformFeedback(null);
  13377. }
  13378. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13379. if (!linked) {
  13380. context.validateProgram(shaderProgram);
  13381. var error = context.getProgramInfoLog(shaderProgram);
  13382. if (error) {
  13383. throw new Error(error);
  13384. }
  13385. }
  13386. context.deleteShader(vertexShader);
  13387. context.deleteShader(fragmentShader);
  13388. return shaderProgram;
  13389. };
  13390. /**
  13391. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13392. * @param shaderProgram defines the webGL program to use
  13393. * @param uniformsNames defines the list of uniform names
  13394. * @returns an array of webGL uniform locations
  13395. */
  13396. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13397. var results = new Array();
  13398. for (var index = 0; index < uniformsNames.length; index++) {
  13399. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13400. }
  13401. return results;
  13402. };
  13403. /**
  13404. * Gets the lsit of active attributes for a given webGL program
  13405. * @param shaderProgram defines the webGL program to use
  13406. * @param attributesNames defines the list of attribute names to get
  13407. * @returns an array of indices indicating the offset of each attribute
  13408. */
  13409. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13410. var results = [];
  13411. for (var index = 0; index < attributesNames.length; index++) {
  13412. try {
  13413. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13414. }
  13415. catch (e) {
  13416. results.push(-1);
  13417. }
  13418. }
  13419. return results;
  13420. };
  13421. /**
  13422. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13423. * @param effect defines the effect to activate
  13424. */
  13425. Engine.prototype.enableEffect = function (effect) {
  13426. if (!effect) {
  13427. return;
  13428. }
  13429. // Use program
  13430. this.bindSamplers(effect);
  13431. this._currentEffect = effect;
  13432. if (effect.onBind) {
  13433. effect.onBind(effect);
  13434. }
  13435. effect.onBindObservable.notifyObservers(effect);
  13436. };
  13437. /**
  13438. * Set the value of an uniform to an array of int32
  13439. * @param uniform defines the webGL uniform location where to store the value
  13440. * @param array defines the array of int32 to store
  13441. */
  13442. Engine.prototype.setIntArray = function (uniform, array) {
  13443. if (!uniform)
  13444. return;
  13445. this._gl.uniform1iv(uniform, array);
  13446. };
  13447. /**
  13448. * Set the value of an uniform to an array of int32 (stored as vec2)
  13449. * @param uniform defines the webGL uniform location where to store the value
  13450. * @param array defines the array of int32 to store
  13451. */
  13452. Engine.prototype.setIntArray2 = function (uniform, array) {
  13453. if (!uniform || array.length % 2 !== 0)
  13454. return;
  13455. this._gl.uniform2iv(uniform, array);
  13456. };
  13457. /**
  13458. * Set the value of an uniform to an array of int32 (stored as vec3)
  13459. * @param uniform defines the webGL uniform location where to store the value
  13460. * @param array defines the array of int32 to store
  13461. */
  13462. Engine.prototype.setIntArray3 = function (uniform, array) {
  13463. if (!uniform || array.length % 3 !== 0)
  13464. return;
  13465. this._gl.uniform3iv(uniform, array);
  13466. };
  13467. /**
  13468. * Set the value of an uniform to an array of int32 (stored as vec4)
  13469. * @param uniform defines the webGL uniform location where to store the value
  13470. * @param array defines the array of int32 to store
  13471. */
  13472. Engine.prototype.setIntArray4 = function (uniform, array) {
  13473. if (!uniform || array.length % 4 !== 0)
  13474. return;
  13475. this._gl.uniform4iv(uniform, array);
  13476. };
  13477. /**
  13478. * Set the value of an uniform to an array of float32
  13479. * @param uniform defines the webGL uniform location where to store the value
  13480. * @param array defines the array of float32 to store
  13481. */
  13482. Engine.prototype.setFloatArray = function (uniform, array) {
  13483. if (!uniform)
  13484. return;
  13485. this._gl.uniform1fv(uniform, array);
  13486. };
  13487. /**
  13488. * Set the value of an uniform to an array of float32 (stored as vec2)
  13489. * @param uniform defines the webGL uniform location where to store the value
  13490. * @param array defines the array of float32 to store
  13491. */
  13492. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13493. if (!uniform || array.length % 2 !== 0)
  13494. return;
  13495. this._gl.uniform2fv(uniform, array);
  13496. };
  13497. /**
  13498. * Set the value of an uniform to an array of float32 (stored as vec3)
  13499. * @param uniform defines the webGL uniform location where to store the value
  13500. * @param array defines the array of float32 to store
  13501. */
  13502. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13503. if (!uniform || array.length % 3 !== 0)
  13504. return;
  13505. this._gl.uniform3fv(uniform, array);
  13506. };
  13507. /**
  13508. * Set the value of an uniform to an array of float32 (stored as vec4)
  13509. * @param uniform defines the webGL uniform location where to store the value
  13510. * @param array defines the array of float32 to store
  13511. */
  13512. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13513. if (!uniform || array.length % 4 !== 0)
  13514. return;
  13515. this._gl.uniform4fv(uniform, array);
  13516. };
  13517. /**
  13518. * Set the value of an uniform to an array of number
  13519. * @param uniform defines the webGL uniform location where to store the value
  13520. * @param array defines the array of number to store
  13521. */
  13522. Engine.prototype.setArray = function (uniform, array) {
  13523. if (!uniform)
  13524. return;
  13525. this._gl.uniform1fv(uniform, array);
  13526. };
  13527. /**
  13528. * Set the value of an uniform to an array of number (stored as vec2)
  13529. * @param uniform defines the webGL uniform location where to store the value
  13530. * @param array defines the array of number to store
  13531. */
  13532. Engine.prototype.setArray2 = function (uniform, array) {
  13533. if (!uniform || array.length % 2 !== 0)
  13534. return;
  13535. this._gl.uniform2fv(uniform, array);
  13536. };
  13537. /**
  13538. * Set the value of an uniform to an array of number (stored as vec3)
  13539. * @param uniform defines the webGL uniform location where to store the value
  13540. * @param array defines the array of number to store
  13541. */
  13542. Engine.prototype.setArray3 = function (uniform, array) {
  13543. if (!uniform || array.length % 3 !== 0)
  13544. return;
  13545. this._gl.uniform3fv(uniform, array);
  13546. };
  13547. /**
  13548. * Set the value of an uniform to an array of number (stored as vec4)
  13549. * @param uniform defines the webGL uniform location where to store the value
  13550. * @param array defines the array of number to store
  13551. */
  13552. Engine.prototype.setArray4 = function (uniform, array) {
  13553. if (!uniform || array.length % 4 !== 0)
  13554. return;
  13555. this._gl.uniform4fv(uniform, array);
  13556. };
  13557. /**
  13558. * Set the value of an uniform to an array of float32 (stored as matrices)
  13559. * @param uniform defines the webGL uniform location where to store the value
  13560. * @param matrices defines the array of float32 to store
  13561. */
  13562. Engine.prototype.setMatrices = function (uniform, matrices) {
  13563. if (!uniform)
  13564. return;
  13565. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13566. };
  13567. /**
  13568. * Set the value of an uniform to a matrix
  13569. * @param uniform defines the webGL uniform location where to store the value
  13570. * @param matrix defines the matrix to store
  13571. */
  13572. Engine.prototype.setMatrix = function (uniform, matrix) {
  13573. if (!uniform)
  13574. return;
  13575. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13576. };
  13577. /**
  13578. * Set the value of an uniform to a matrix (3x3)
  13579. * @param uniform defines the webGL uniform location where to store the value
  13580. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13581. */
  13582. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13583. if (!uniform)
  13584. return;
  13585. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13586. };
  13587. /**
  13588. * Set the value of an uniform to a matrix (2x2)
  13589. * @param uniform defines the webGL uniform location where to store the value
  13590. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13591. */
  13592. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13593. if (!uniform)
  13594. return;
  13595. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13596. };
  13597. /**
  13598. * Set the value of an uniform to a number (int)
  13599. * @param uniform defines the webGL uniform location where to store the value
  13600. * @param value defines the int number to store
  13601. */
  13602. Engine.prototype.setInt = function (uniform, value) {
  13603. if (!uniform)
  13604. return;
  13605. this._gl.uniform1i(uniform, value);
  13606. };
  13607. /**
  13608. * Set the value of an uniform to a number (float)
  13609. * @param uniform defines the webGL uniform location where to store the value
  13610. * @param value defines the float number to store
  13611. */
  13612. Engine.prototype.setFloat = function (uniform, value) {
  13613. if (!uniform)
  13614. return;
  13615. this._gl.uniform1f(uniform, value);
  13616. };
  13617. /**
  13618. * Set the value of an uniform to a vec2
  13619. * @param uniform defines the webGL uniform location where to store the value
  13620. * @param x defines the 1st component of the value
  13621. * @param y defines the 2nd component of the value
  13622. */
  13623. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13624. if (!uniform)
  13625. return;
  13626. this._gl.uniform2f(uniform, x, y);
  13627. };
  13628. /**
  13629. * Set the value of an uniform to a vec3
  13630. * @param uniform defines the webGL uniform location where to store the value
  13631. * @param x defines the 1st component of the value
  13632. * @param y defines the 2nd component of the value
  13633. * @param z defines the 3rd component of the value
  13634. */
  13635. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13636. if (!uniform)
  13637. return;
  13638. this._gl.uniform3f(uniform, x, y, z);
  13639. };
  13640. /**
  13641. * Set the value of an uniform to a boolean
  13642. * @param uniform defines the webGL uniform location where to store the value
  13643. * @param bool defines the boolean to store
  13644. */
  13645. Engine.prototype.setBool = function (uniform, bool) {
  13646. if (!uniform)
  13647. return;
  13648. this._gl.uniform1i(uniform, bool);
  13649. };
  13650. /**
  13651. * Set the value of an uniform to a vec4
  13652. * @param uniform defines the webGL uniform location where to store the value
  13653. * @param x defines the 1st component of the value
  13654. * @param y defines the 2nd component of the value
  13655. * @param z defines the 3rd component of the value
  13656. * @param w defines the 4th component of the value
  13657. */
  13658. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13659. if (!uniform)
  13660. return;
  13661. this._gl.uniform4f(uniform, x, y, z, w);
  13662. };
  13663. /**
  13664. * Set the value of an uniform to a Color3
  13665. * @param uniform defines the webGL uniform location where to store the value
  13666. * @param color3 defines the color to store
  13667. */
  13668. Engine.prototype.setColor3 = function (uniform, color3) {
  13669. if (!uniform)
  13670. return;
  13671. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13672. };
  13673. /**
  13674. * Set the value of an uniform to a Color3 and an alpha value
  13675. * @param uniform defines the webGL uniform location where to store the value
  13676. * @param color3 defines the color to store
  13677. * @param alpha defines the alpha component to store
  13678. */
  13679. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13680. if (!uniform)
  13681. return;
  13682. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13683. };
  13684. /**
  13685. * Sets a Color4 on a uniform variable
  13686. * @param uniform defines the uniform location
  13687. * @param color4 defines the value to be set
  13688. */
  13689. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13690. if (!uniform)
  13691. return;
  13692. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13693. };
  13694. // States
  13695. /**
  13696. * Set various states to the webGL context
  13697. * @param culling defines backface culling state
  13698. * @param zOffset defines the value to apply to zOffset (0 by default)
  13699. * @param force defines if states must be applied even if cache is up to date
  13700. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13701. */
  13702. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13703. if (zOffset === void 0) { zOffset = 0; }
  13704. if (reverseSide === void 0) { reverseSide = false; }
  13705. // Culling
  13706. if (this._depthCullingState.cull !== culling || force) {
  13707. this._depthCullingState.cull = culling;
  13708. }
  13709. // Cull face
  13710. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13711. if (this._depthCullingState.cullFace !== cullFace || force) {
  13712. this._depthCullingState.cullFace = cullFace;
  13713. }
  13714. // Z offset
  13715. this.setZOffset(zOffset);
  13716. // Front face
  13717. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13718. if (this._depthCullingState.frontFace !== frontFace || force) {
  13719. this._depthCullingState.frontFace = frontFace;
  13720. }
  13721. };
  13722. /**
  13723. * Set the z offset to apply to current rendering
  13724. * @param value defines the offset to apply
  13725. */
  13726. Engine.prototype.setZOffset = function (value) {
  13727. this._depthCullingState.zOffset = value;
  13728. };
  13729. /**
  13730. * Gets the current value of the zOffset
  13731. * @returns the current zOffset state
  13732. */
  13733. Engine.prototype.getZOffset = function () {
  13734. return this._depthCullingState.zOffset;
  13735. };
  13736. /**
  13737. * Enable or disable depth buffering
  13738. * @param enable defines the state to set
  13739. */
  13740. Engine.prototype.setDepthBuffer = function (enable) {
  13741. this._depthCullingState.depthTest = enable;
  13742. };
  13743. /**
  13744. * Gets a boolean indicating if depth writing is enabled
  13745. * @returns the current depth writing state
  13746. */
  13747. Engine.prototype.getDepthWrite = function () {
  13748. return this._depthCullingState.depthMask;
  13749. };
  13750. /**
  13751. * Enable or disable depth writing
  13752. * @param enable defines the state to set
  13753. */
  13754. Engine.prototype.setDepthWrite = function (enable) {
  13755. this._depthCullingState.depthMask = enable;
  13756. };
  13757. /**
  13758. * Enable or disable color writing
  13759. * @param enable defines the state to set
  13760. */
  13761. Engine.prototype.setColorWrite = function (enable) {
  13762. this._gl.colorMask(enable, enable, enable, enable);
  13763. this._colorWrite = enable;
  13764. };
  13765. /**
  13766. * Gets a boolean indicating if color writing is enabled
  13767. * @returns the current color writing state
  13768. */
  13769. Engine.prototype.getColorWrite = function () {
  13770. return this._colorWrite;
  13771. };
  13772. /**
  13773. * Sets alpha constants used by some alpha blending modes
  13774. * @param r defines the red component
  13775. * @param g defines the green component
  13776. * @param b defines the blue component
  13777. * @param a defines the alpha component
  13778. */
  13779. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13780. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13781. };
  13782. /**
  13783. * Sets the current alpha mode
  13784. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  13785. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  13786. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13787. */
  13788. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13789. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13790. if (this._alphaMode === mode) {
  13791. return;
  13792. }
  13793. switch (mode) {
  13794. case Engine.ALPHA_DISABLE:
  13795. this._alphaState.alphaBlend = false;
  13796. break;
  13797. case Engine.ALPHA_PREMULTIPLIED:
  13798. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13799. this._alphaState.alphaBlend = true;
  13800. break;
  13801. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13802. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13803. this._alphaState.alphaBlend = true;
  13804. break;
  13805. case Engine.ALPHA_COMBINE:
  13806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13807. this._alphaState.alphaBlend = true;
  13808. break;
  13809. case Engine.ALPHA_ONEONE:
  13810. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13811. this._alphaState.alphaBlend = true;
  13812. break;
  13813. case Engine.ALPHA_ADD:
  13814. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13815. this._alphaState.alphaBlend = true;
  13816. break;
  13817. case Engine.ALPHA_SUBTRACT:
  13818. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13819. this._alphaState.alphaBlend = true;
  13820. break;
  13821. case Engine.ALPHA_MULTIPLY:
  13822. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13823. this._alphaState.alphaBlend = true;
  13824. break;
  13825. case Engine.ALPHA_MAXIMIZED:
  13826. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13827. this._alphaState.alphaBlend = true;
  13828. break;
  13829. case Engine.ALPHA_INTERPOLATE:
  13830. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13831. this._alphaState.alphaBlend = true;
  13832. break;
  13833. case Engine.ALPHA_SCREENMODE:
  13834. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13835. this._alphaState.alphaBlend = true;
  13836. break;
  13837. }
  13838. if (!noDepthWriteChange) {
  13839. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13840. }
  13841. this._alphaMode = mode;
  13842. };
  13843. /**
  13844. * Gets the current alpha mode
  13845. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13846. * @returns the current alpha mode
  13847. */
  13848. Engine.prototype.getAlphaMode = function () {
  13849. return this._alphaMode;
  13850. };
  13851. // Textures
  13852. /**
  13853. * Force the entire cache to be cleared
  13854. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  13855. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  13856. */
  13857. Engine.prototype.wipeCaches = function (bruteForce) {
  13858. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13859. return;
  13860. }
  13861. this._currentEffect = null;
  13862. if (bruteForce) {
  13863. this.resetTextureCache();
  13864. this._currentProgram = null;
  13865. this._stencilState.reset();
  13866. this._depthCullingState.reset();
  13867. this.setDepthFunctionToLessOrEqual();
  13868. this._alphaState.reset();
  13869. }
  13870. this._resetVertexBufferBinding();
  13871. this._cachedIndexBuffer = null;
  13872. this._cachedEffectForVertexBuffers = null;
  13873. this._unbindVertexArrayObject();
  13874. this.bindIndexBuffer(null);
  13875. };
  13876. /**
  13877. * Set the compressed texture format to use, based on the formats you have, and the formats
  13878. * supported by the hardware / browser.
  13879. *
  13880. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13881. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13882. * to API arguments needed to compressed textures. This puts the burden on the container
  13883. * generator to house the arcane code for determining these for current & future formats.
  13884. *
  13885. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13886. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13887. *
  13888. * Note: The result of this call is not taken into account when a texture is base64.
  13889. *
  13890. * @param formatsAvailable defines the list of those format families you have created
  13891. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13892. *
  13893. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13894. * @returns The extension selected.
  13895. */
  13896. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13897. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13898. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13899. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13900. return this._textureFormatInUse = this._texturesSupported[i];
  13901. }
  13902. }
  13903. }
  13904. // actively set format to nothing, to allow this to be called more than once
  13905. // and possibly fail the 2nd time
  13906. this._textureFormatInUse = null;
  13907. return null;
  13908. };
  13909. /** @ignore */
  13910. Engine.prototype._createTexture = function () {
  13911. var texture = this._gl.createTexture();
  13912. if (!texture) {
  13913. throw new Error("Unable to create texture");
  13914. }
  13915. return texture;
  13916. };
  13917. /**
  13918. * Usually called from BABYLON.Texture.ts.
  13919. * Passed information to create a WebGLTexture
  13920. * @param urlArg defines a value which contains one of the following:
  13921. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  13922. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13923. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13924. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  13925. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  13926. * @param scene needed for loading to the correct scene
  13927. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  13928. * @param onLoad optional callback to be called upon successful completion
  13929. * @param onError optional callback to be called upon failure
  13930. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13931. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  13932. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  13933. * @returns a InternalTexture for assignment back into BABYLON.Texture
  13934. */
  13935. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  13936. var _this = this;
  13937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13938. if (onLoad === void 0) { onLoad = null; }
  13939. if (onError === void 0) { onError = null; }
  13940. if (buffer === void 0) { buffer = null; }
  13941. if (fallback === void 0) { fallback = null; }
  13942. if (format === void 0) { format = null; }
  13943. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13944. var fromData = url.substr(0, 5) === "data:";
  13945. var fromBlob = url.substr(0, 5) === "blob:";
  13946. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13947. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13948. // establish the file extension, if possible
  13949. var lastDot = url.lastIndexOf('.');
  13950. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13951. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13952. var isTGA = (extension.indexOf(".tga") === 0);
  13953. // determine if a ktx file should be substituted
  13954. var isKTX = false;
  13955. if (this._textureFormatInUse && !isBase64 && !fallback) {
  13956. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13957. isKTX = true;
  13958. }
  13959. if (scene) {
  13960. scene._addPendingData(texture);
  13961. }
  13962. texture.url = url;
  13963. texture.generateMipMaps = !noMipmap;
  13964. texture.samplingMode = samplingMode;
  13965. texture.invertY = invertY;
  13966. if (!this._doNotHandleContextLost) {
  13967. // Keep a link to the buffer only if we plan to handle context lost
  13968. texture._buffer = buffer;
  13969. }
  13970. var onLoadObserver = null;
  13971. if (onLoad && !fallback) {
  13972. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13973. }
  13974. if (!fallback)
  13975. this._internalTexturesCache.push(texture);
  13976. var onerror = function (message, exception) {
  13977. if (scene) {
  13978. scene._removePendingData(texture);
  13979. }
  13980. if (onLoadObserver) {
  13981. texture.onLoadedObservable.remove(onLoadObserver);
  13982. }
  13983. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13984. if (isKTX) {
  13985. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13986. }
  13987. else if (BABYLON.Tools.UseFallbackTexture) {
  13988. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13989. }
  13990. if (onError) {
  13991. onError(message || "Unknown error", exception);
  13992. }
  13993. };
  13994. var callback = null;
  13995. // processing for non-image formats
  13996. if (isKTX || isTGA || isDDS) {
  13997. if (isKTX) {
  13998. callback = function (data) {
  13999. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14000. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14001. ktx.uploadLevels(_this._gl, !noMipmap);
  14002. return false;
  14003. }, samplingMode);
  14004. };
  14005. }
  14006. else if (isTGA) {
  14007. callback = function (arrayBuffer) {
  14008. var data = new Uint8Array(arrayBuffer);
  14009. var header = BABYLON.TGATools.GetTGAHeader(data);
  14010. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14011. BABYLON.TGATools.UploadContent(_this._gl, data);
  14012. return false;
  14013. }, samplingMode);
  14014. };
  14015. }
  14016. else if (isDDS) {
  14017. callback = function (data) {
  14018. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14019. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14020. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14021. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14022. return false;
  14023. }, samplingMode);
  14024. };
  14025. }
  14026. if (!buffer) {
  14027. this._loadFile(url, function (data) {
  14028. if (callback) {
  14029. callback(data);
  14030. }
  14031. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14032. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14033. });
  14034. }
  14035. else {
  14036. if (callback) {
  14037. callback(buffer);
  14038. }
  14039. }
  14040. // image format processing
  14041. }
  14042. else {
  14043. var onload = function (img) {
  14044. if (fromBlob && !_this._doNotHandleContextLost) {
  14045. // We need to store the image if we need to rebuild the texture
  14046. // in case of a webgl context lost
  14047. texture._buffer = img;
  14048. }
  14049. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14050. var gl = _this._gl;
  14051. var isPot = (img.width === potWidth && img.height === potHeight);
  14052. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14053. if (isPot) {
  14054. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14055. return false;
  14056. }
  14057. // Using shaders to rescale because canvas.drawImage is lossy
  14058. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14059. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14060. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14065. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14066. _this._releaseTexture(source);
  14067. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14068. continuationCallback();
  14069. });
  14070. return true;
  14071. }, samplingMode);
  14072. };
  14073. if (!fromData || isBase64)
  14074. if (buffer instanceof HTMLImageElement) {
  14075. onload(buffer);
  14076. }
  14077. else {
  14078. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14079. }
  14080. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14081. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14082. else
  14083. onload(buffer);
  14084. }
  14085. return texture;
  14086. };
  14087. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14088. var _this = this;
  14089. var rtt = this.createRenderTargetTexture({
  14090. width: destination.width,
  14091. height: destination.height,
  14092. }, {
  14093. generateMipMaps: false,
  14094. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14095. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14096. generateDepthBuffer: false,
  14097. generateStencilBuffer: false
  14098. });
  14099. if (!this._rescalePostProcess) {
  14100. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14101. }
  14102. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14103. _this._rescalePostProcess.onApply = function (effect) {
  14104. effect._bindTexture("textureSampler", source);
  14105. };
  14106. var hostingScene = scene;
  14107. if (!hostingScene) {
  14108. hostingScene = _this.scenes[_this.scenes.length - 1];
  14109. }
  14110. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14111. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14112. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14113. _this.unBindFramebuffer(rtt);
  14114. _this._releaseTexture(rtt);
  14115. if (onComplete) {
  14116. onComplete();
  14117. }
  14118. });
  14119. };
  14120. /**
  14121. * Update a raw texture
  14122. * @param texture defines the texture to update
  14123. * @param data defines the data to store in the texture
  14124. * @param format defines the format of the data
  14125. * @param invertY defines if data must be stored with Y axis inverted
  14126. * @param compression defines the compression used (null by default)
  14127. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14128. */
  14129. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14130. if (compression === void 0) { compression = null; }
  14131. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14132. if (!texture) {
  14133. return;
  14134. }
  14135. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14136. var internalFormat = this._getInternalFormat(format);
  14137. var textureType = this._getWebGLTextureType(type);
  14138. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14139. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14140. if (!this._doNotHandleContextLost) {
  14141. texture._bufferView = data;
  14142. texture.format = format;
  14143. texture.type = type;
  14144. texture.invertY = invertY;
  14145. texture._compression = compression;
  14146. }
  14147. if (texture.width % 4 !== 0) {
  14148. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14149. }
  14150. if (compression && data) {
  14151. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14152. }
  14153. else {
  14154. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14155. }
  14156. if (texture.generateMipMaps) {
  14157. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14158. }
  14159. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14160. // this.resetTextureCache();
  14161. texture.isReady = true;
  14162. };
  14163. /**
  14164. * Creates a raw texture
  14165. * @param data defines the data to store in the texture
  14166. * @param width defines the width of the texture
  14167. * @param height defines the height of the texture
  14168. * @param format defines the format of the data
  14169. * @param generateMipMaps defines if the engine should generate the mip levels
  14170. * @param invertY defines if data must be stored with Y axis inverted
  14171. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14172. * @param compression defines the compression used (null by default)
  14173. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14174. * @returns the raw texture inside an InternalTexture
  14175. */
  14176. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14177. if (compression === void 0) { compression = null; }
  14178. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14180. texture.baseWidth = width;
  14181. texture.baseHeight = height;
  14182. texture.width = width;
  14183. texture.height = height;
  14184. texture.format = format;
  14185. texture.generateMipMaps = generateMipMaps;
  14186. texture.samplingMode = samplingMode;
  14187. texture.invertY = invertY;
  14188. texture._compression = compression;
  14189. texture.type = type;
  14190. if (!this._doNotHandleContextLost) {
  14191. texture._bufferView = data;
  14192. }
  14193. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14194. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14195. // Filters
  14196. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14197. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14198. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14199. if (generateMipMaps) {
  14200. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14201. }
  14202. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14203. this._internalTexturesCache.push(texture);
  14204. return texture;
  14205. };
  14206. /**
  14207. * Creates a dynamic texture
  14208. * @param width defines the width of the texture
  14209. * @param height defines the height of the texture
  14210. * @param generateMipMaps defines if the engine should generate the mip levels
  14211. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14212. * @returns the dynamic texture inside an InternalTexture
  14213. */
  14214. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14215. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14216. texture.baseWidth = width;
  14217. texture.baseHeight = height;
  14218. if (generateMipMaps) {
  14219. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14220. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14221. }
  14222. // this.resetTextureCache();
  14223. texture.width = width;
  14224. texture.height = height;
  14225. texture.isReady = false;
  14226. texture.generateMipMaps = generateMipMaps;
  14227. texture.samplingMode = samplingMode;
  14228. this.updateTextureSamplingMode(samplingMode, texture);
  14229. this._internalTexturesCache.push(texture);
  14230. return texture;
  14231. };
  14232. /**
  14233. * Update the sampling mode of a given texture
  14234. * @param samplingMode defines the required sampling mode
  14235. * @param texture defines the texture to update
  14236. */
  14237. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14238. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14239. if (texture.isCube) {
  14240. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14241. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14242. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14243. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14244. }
  14245. else if (texture.is3D) {
  14246. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14247. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14248. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14249. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14250. }
  14251. else {
  14252. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14253. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14254. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14255. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14256. }
  14257. texture.samplingMode = samplingMode;
  14258. };
  14259. /**
  14260. * Update the content of a dynamic texture
  14261. * @param texture defines the texture to update
  14262. * @param canvas defines the canvas containing the source
  14263. * @param invertY defines if data must be stored with Y axis inverted
  14264. * @param premulAlpha defines if alpha is stored as premultiplied
  14265. * @param format defines the format of the data
  14266. */
  14267. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14268. if (premulAlpha === void 0) { premulAlpha = false; }
  14269. if (!texture) {
  14270. return;
  14271. }
  14272. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14273. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14274. if (premulAlpha) {
  14275. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14276. }
  14277. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14278. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14279. if (texture.generateMipMaps) {
  14280. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14281. }
  14282. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14283. if (premulAlpha) {
  14284. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14285. }
  14286. texture.isReady = true;
  14287. };
  14288. /**
  14289. * Update a video texture
  14290. * @param texture defines the texture to update
  14291. * @param video defines the video element to use
  14292. * @param invertY defines if data must be stored with Y axis inverted
  14293. */
  14294. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14295. if (!texture || texture._isDisabled) {
  14296. return;
  14297. }
  14298. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14299. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14300. try {
  14301. // Testing video texture support
  14302. if (this._videoTextureSupported === undefined) {
  14303. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14304. if (this._gl.getError() !== 0) {
  14305. this._videoTextureSupported = false;
  14306. }
  14307. else {
  14308. this._videoTextureSupported = true;
  14309. }
  14310. }
  14311. // Copy video through the current working canvas if video texture is not supported
  14312. if (!this._videoTextureSupported) {
  14313. if (!texture._workingCanvas) {
  14314. texture._workingCanvas = document.createElement("canvas");
  14315. var context = texture._workingCanvas.getContext("2d");
  14316. if (!context) {
  14317. throw new Error("Unable to get 2d context");
  14318. }
  14319. texture._workingContext = context;
  14320. texture._workingCanvas.width = texture.width;
  14321. texture._workingCanvas.height = texture.height;
  14322. }
  14323. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14325. }
  14326. else {
  14327. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14328. }
  14329. if (texture.generateMipMaps) {
  14330. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14331. }
  14332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14333. // this.resetTextureCache();
  14334. texture.isReady = true;
  14335. }
  14336. catch (ex) {
  14337. // Something unexpected
  14338. // Let's disable the texture
  14339. texture._isDisabled = true;
  14340. }
  14341. };
  14342. /**
  14343. * Updates a depth texture Comparison Mode and Function.
  14344. * If the comparison Function is equal to 0, the mode will be set to none.
  14345. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14346. * @param texture The texture to set the comparison function for
  14347. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14348. */
  14349. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14350. if (this.webGLVersion === 1) {
  14351. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14352. return;
  14353. }
  14354. var gl = this._gl;
  14355. if (texture.isCube) {
  14356. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14357. if (comparisonFunction === 0) {
  14358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14360. }
  14361. else {
  14362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14364. }
  14365. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14366. }
  14367. else {
  14368. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14369. if (comparisonFunction === 0) {
  14370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14372. }
  14373. else {
  14374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14376. }
  14377. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14378. }
  14379. texture._comparisonFunction = comparisonFunction;
  14380. };
  14381. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14382. var width = size.width || size;
  14383. var height = size.height || size;
  14384. internalTexture.baseWidth = width;
  14385. internalTexture.baseHeight = height;
  14386. internalTexture.width = width;
  14387. internalTexture.height = height;
  14388. internalTexture.isReady = true;
  14389. internalTexture.samples = 1;
  14390. internalTexture.generateMipMaps = false;
  14391. internalTexture._generateDepthBuffer = true;
  14392. internalTexture._generateStencilBuffer = generateStencil;
  14393. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14394. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14395. internalTexture._comparisonFunction = comparisonFunction;
  14396. var gl = this._gl;
  14397. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14398. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14399. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14400. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14401. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14402. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14403. if (comparisonFunction === 0) {
  14404. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14405. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14406. }
  14407. else {
  14408. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14409. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14410. }
  14411. };
  14412. /**
  14413. * Creates a depth stencil texture.
  14414. * This is only available in WebGL 2 or with the depth texture extension available.
  14415. * @param size The size of face edge in the texture.
  14416. * @param options The options defining the texture.
  14417. * @returns The texture
  14418. */
  14419. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14420. if (options.isCube) {
  14421. var width = size.width || size;
  14422. return this._createDepthStencilCubeTexture(width, options);
  14423. }
  14424. else {
  14425. return this._createDepthStencilTexture(size, options);
  14426. }
  14427. };
  14428. /**
  14429. * Creates a depth stencil texture.
  14430. * This is only available in WebGL 2 or with the depth texture extension available.
  14431. * @param size The size of face edge in the texture.
  14432. * @param options The options defining the texture.
  14433. * @returns The texture
  14434. */
  14435. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14436. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14437. if (!this._caps.depthTextureExtension) {
  14438. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14439. return internalTexture;
  14440. }
  14441. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14442. var gl = this._gl;
  14443. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14444. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14445. if (this.webGLVersion > 1) {
  14446. if (internalOptions.generateStencil) {
  14447. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14448. }
  14449. else {
  14450. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14451. }
  14452. }
  14453. else {
  14454. if (internalOptions.generateStencil) {
  14455. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14456. }
  14457. else {
  14458. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14459. }
  14460. }
  14461. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14462. return internalTexture;
  14463. };
  14464. /**
  14465. * Creates a depth stencil cube texture.
  14466. * This is only available in WebGL 2.
  14467. * @param size The size of face edge in the cube texture.
  14468. * @param options The options defining the cube texture.
  14469. * @returns The cube texture
  14470. */
  14471. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14472. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14473. internalTexture.isCube = true;
  14474. if (this.webGLVersion === 1) {
  14475. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14476. return internalTexture;
  14477. }
  14478. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14479. var gl = this._gl;
  14480. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14481. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14482. // Create the depth/stencil buffer
  14483. for (var face = 0; face < 6; face++) {
  14484. if (internalOptions.generateStencil) {
  14485. 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);
  14486. }
  14487. else {
  14488. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14489. }
  14490. }
  14491. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14492. return internalTexture;
  14493. };
  14494. /**
  14495. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14496. * @param renderTarget The render target to set the frame buffer for
  14497. */
  14498. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14499. // Create the framebuffer
  14500. var internalTexture = renderTarget.getInternalTexture();
  14501. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14502. return;
  14503. }
  14504. var gl = this._gl;
  14505. var depthStencilTexture = renderTarget.depthStencilTexture;
  14506. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14507. if (depthStencilTexture.isCube) {
  14508. if (depthStencilTexture._generateStencilBuffer) {
  14509. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14510. }
  14511. else {
  14512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14513. }
  14514. }
  14515. else {
  14516. if (depthStencilTexture._generateStencilBuffer) {
  14517. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14518. }
  14519. else {
  14520. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14521. }
  14522. }
  14523. this.bindUnboundFramebuffer(null);
  14524. };
  14525. /**
  14526. * Creates a new render target texture
  14527. * @param size defines the size of the texture
  14528. * @param options defines the options used to create the texture
  14529. * @returns a new render target texture stored in an InternalTexture
  14530. */
  14531. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14532. var fullOptions = new RenderTargetCreationOptions();
  14533. if (options !== undefined && typeof options === "object") {
  14534. fullOptions.generateMipMaps = options.generateMipMaps;
  14535. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14536. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14537. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14538. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14539. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14540. }
  14541. else {
  14542. fullOptions.generateMipMaps = options;
  14543. fullOptions.generateDepthBuffer = true;
  14544. fullOptions.generateStencilBuffer = false;
  14545. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14546. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14547. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14548. }
  14549. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14550. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14551. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14552. }
  14553. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14554. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14555. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14556. }
  14557. var gl = this._gl;
  14558. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14559. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14560. var width = size.width || size;
  14561. var height = size.height || size;
  14562. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14563. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14564. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14565. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14566. }
  14567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14571. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14572. // Create the framebuffer
  14573. var framebuffer = gl.createFramebuffer();
  14574. this.bindUnboundFramebuffer(framebuffer);
  14575. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14576. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14577. if (fullOptions.generateMipMaps) {
  14578. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14579. }
  14580. // Unbind
  14581. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14582. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14583. this.bindUnboundFramebuffer(null);
  14584. texture._framebuffer = framebuffer;
  14585. texture.baseWidth = width;
  14586. texture.baseHeight = height;
  14587. texture.width = width;
  14588. texture.height = height;
  14589. texture.isReady = true;
  14590. texture.samples = 1;
  14591. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14592. texture.samplingMode = fullOptions.samplingMode;
  14593. texture.type = fullOptions.type;
  14594. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14595. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14596. // this.resetTextureCache();
  14597. this._internalTexturesCache.push(texture);
  14598. return texture;
  14599. };
  14600. /**
  14601. * Create a multi render target texture
  14602. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14603. * @param size defines the size of the texture
  14604. * @param options defines the creation options
  14605. * @returns the cube texture as an InternalTexture
  14606. */
  14607. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14608. var generateMipMaps = false;
  14609. var generateDepthBuffer = true;
  14610. var generateStencilBuffer = false;
  14611. var generateDepthTexture = false;
  14612. var textureCount = 1;
  14613. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14614. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14615. var types = new Array();
  14616. var samplingModes = new Array();
  14617. if (options !== undefined) {
  14618. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14619. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14620. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14621. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14622. textureCount = options.textureCount || 1;
  14623. if (options.types) {
  14624. types = options.types;
  14625. }
  14626. if (options.samplingModes) {
  14627. samplingModes = options.samplingModes;
  14628. }
  14629. }
  14630. var gl = this._gl;
  14631. // Create the framebuffer
  14632. var framebuffer = gl.createFramebuffer();
  14633. this.bindUnboundFramebuffer(framebuffer);
  14634. var width = size.width || size;
  14635. var height = size.height || size;
  14636. var textures = [];
  14637. var attachments = [];
  14638. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14639. for (var i = 0; i < textureCount; i++) {
  14640. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14641. var type = types[i] || defaultType;
  14642. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14643. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14644. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14645. }
  14646. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14647. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14648. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14649. }
  14650. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14651. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14652. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14653. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14654. }
  14655. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14656. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14657. textures.push(texture);
  14658. attachments.push(attachment);
  14659. gl.activeTexture(gl["TEXTURE" + i]);
  14660. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14662. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14663. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14664. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14665. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14666. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14667. if (generateMipMaps) {
  14668. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14669. }
  14670. // Unbind
  14671. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14672. texture._framebuffer = framebuffer;
  14673. texture._depthStencilBuffer = depthStencilBuffer;
  14674. texture.baseWidth = width;
  14675. texture.baseHeight = height;
  14676. texture.width = width;
  14677. texture.height = height;
  14678. texture.isReady = true;
  14679. texture.samples = 1;
  14680. texture.generateMipMaps = generateMipMaps;
  14681. texture.samplingMode = samplingMode;
  14682. texture.type = type;
  14683. texture._generateDepthBuffer = generateDepthBuffer;
  14684. texture._generateStencilBuffer = generateStencilBuffer;
  14685. texture._attachments = attachments;
  14686. this._internalTexturesCache.push(texture);
  14687. }
  14688. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14689. // Depth texture
  14690. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14691. gl.activeTexture(gl.TEXTURE0);
  14692. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14695. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14697. 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);
  14698. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  14699. depthTexture._framebuffer = framebuffer;
  14700. depthTexture.baseWidth = width;
  14701. depthTexture.baseHeight = height;
  14702. depthTexture.width = width;
  14703. depthTexture.height = height;
  14704. depthTexture.isReady = true;
  14705. depthTexture.samples = 1;
  14706. depthTexture.generateMipMaps = generateMipMaps;
  14707. depthTexture.samplingMode = gl.NEAREST;
  14708. depthTexture._generateDepthBuffer = generateDepthBuffer;
  14709. depthTexture._generateStencilBuffer = generateStencilBuffer;
  14710. textures.push(depthTexture);
  14711. this._internalTexturesCache.push(depthTexture);
  14712. }
  14713. gl.drawBuffers(attachments);
  14714. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14715. this.bindUnboundFramebuffer(null);
  14716. this.resetTextureCache();
  14717. return textures;
  14718. };
  14719. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  14720. if (samples === void 0) { samples = 1; }
  14721. var depthStencilBuffer = null;
  14722. var gl = this._gl;
  14723. // Create the depth/stencil buffer
  14724. if (generateStencilBuffer) {
  14725. depthStencilBuffer = gl.createRenderbuffer();
  14726. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14727. if (samples > 1) {
  14728. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  14729. }
  14730. else {
  14731. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  14732. }
  14733. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14734. }
  14735. else if (generateDepthBuffer) {
  14736. depthStencilBuffer = gl.createRenderbuffer();
  14737. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14738. if (samples > 1) {
  14739. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  14740. }
  14741. else {
  14742. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  14743. }
  14744. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14745. }
  14746. return depthStencilBuffer;
  14747. };
  14748. /**
  14749. * Updates the sample count of a render target texture
  14750. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14751. * @param texture defines the texture to update
  14752. * @param samples defines the sample count to set
  14753. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14754. */
  14755. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  14756. if (this.webGLVersion < 2 || !texture) {
  14757. return 1;
  14758. }
  14759. if (texture.samples === samples) {
  14760. return samples;
  14761. }
  14762. var gl = this._gl;
  14763. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14764. // Dispose previous render buffers
  14765. if (texture._depthStencilBuffer) {
  14766. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14767. texture._depthStencilBuffer = null;
  14768. }
  14769. if (texture._MSAAFramebuffer) {
  14770. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14771. texture._MSAAFramebuffer = null;
  14772. }
  14773. if (texture._MSAARenderBuffer) {
  14774. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14775. texture._MSAARenderBuffer = null;
  14776. }
  14777. if (samples > 1) {
  14778. var framebuffer = gl.createFramebuffer();
  14779. if (!framebuffer) {
  14780. throw new Error("Unable to create multi sampled framebuffer");
  14781. }
  14782. texture._MSAAFramebuffer = framebuffer;
  14783. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  14784. var colorRenderbuffer = gl.createRenderbuffer();
  14785. if (!colorRenderbuffer) {
  14786. throw new Error("Unable to create multi sampled framebuffer");
  14787. }
  14788. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14789. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14790. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  14791. texture._MSAARenderBuffer = colorRenderbuffer;
  14792. }
  14793. else {
  14794. this.bindUnboundFramebuffer(texture._framebuffer);
  14795. }
  14796. texture.samples = samples;
  14797. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  14798. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14799. this.bindUnboundFramebuffer(null);
  14800. return samples;
  14801. };
  14802. /**
  14803. * Update the sample count for a given multiple render target texture
  14804. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14805. * @param textures defines the textures to update
  14806. * @param samples defines the sample count to set
  14807. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14808. */
  14809. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  14810. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  14811. return 1;
  14812. }
  14813. if (textures[0].samples === samples) {
  14814. return samples;
  14815. }
  14816. var gl = this._gl;
  14817. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14818. // Dispose previous render buffers
  14819. if (textures[0]._depthStencilBuffer) {
  14820. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  14821. textures[0]._depthStencilBuffer = null;
  14822. }
  14823. if (textures[0]._MSAAFramebuffer) {
  14824. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  14825. textures[0]._MSAAFramebuffer = null;
  14826. }
  14827. for (var i = 0; i < textures.length; i++) {
  14828. if (textures[i]._MSAARenderBuffer) {
  14829. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  14830. textures[i]._MSAARenderBuffer = null;
  14831. }
  14832. }
  14833. if (samples > 1) {
  14834. var framebuffer = gl.createFramebuffer();
  14835. if (!framebuffer) {
  14836. throw new Error("Unable to create multi sampled framebuffer");
  14837. }
  14838. this.bindUnboundFramebuffer(framebuffer);
  14839. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  14840. var attachments = [];
  14841. for (var i = 0; i < textures.length; i++) {
  14842. var texture = textures[i];
  14843. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14844. var colorRenderbuffer = gl.createRenderbuffer();
  14845. if (!colorRenderbuffer) {
  14846. throw new Error("Unable to create multi sampled framebuffer");
  14847. }
  14848. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14849. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14850. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14851. texture._MSAAFramebuffer = framebuffer;
  14852. texture._MSAARenderBuffer = colorRenderbuffer;
  14853. texture.samples = samples;
  14854. texture._depthStencilBuffer = depthStencilBuffer;
  14855. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14856. attachments.push(attachment);
  14857. }
  14858. gl.drawBuffers(attachments);
  14859. }
  14860. else {
  14861. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14862. }
  14863. this.bindUnboundFramebuffer(null);
  14864. return samples;
  14865. };
  14866. /** @ignore */
  14867. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14868. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14869. };
  14870. /** @ignore */
  14871. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14872. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14873. };
  14874. /**
  14875. * Creates a new render target cube texture
  14876. * @param size defines the size of the texture
  14877. * @param options defines the options used to create the texture
  14878. * @returns a new render target cube texture stored in an InternalTexture
  14879. */
  14880. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14881. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14882. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14883. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14884. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14885. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14886. }
  14887. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14888. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14889. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14890. }
  14891. var gl = this._gl;
  14892. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14893. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14894. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14895. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14896. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14897. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14898. }
  14899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14903. for (var face = 0; face < 6; face++) {
  14904. 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);
  14905. }
  14906. // Create the framebuffer
  14907. var framebuffer = gl.createFramebuffer();
  14908. this.bindUnboundFramebuffer(framebuffer);
  14909. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14910. // MipMaps
  14911. if (fullOptions.generateMipMaps) {
  14912. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14913. }
  14914. // Unbind
  14915. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14916. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14917. this.bindUnboundFramebuffer(null);
  14918. texture._framebuffer = framebuffer;
  14919. texture.width = size;
  14920. texture.height = size;
  14921. texture.isReady = true;
  14922. texture.isCube = true;
  14923. texture.samples = 1;
  14924. texture.generateMipMaps = fullOptions.generateMipMaps;
  14925. texture.samplingMode = fullOptions.samplingMode;
  14926. texture.type = fullOptions.type;
  14927. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14928. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14929. this._internalTexturesCache.push(texture);
  14930. return texture;
  14931. };
  14932. /**
  14933. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  14934. * @param rootUrl defines the url where the file to load is located
  14935. * @param scene defines the current scene
  14936. * @param scale defines scale to apply to the mip map selection
  14937. * @param offset defines offset to apply to the mip map selection
  14938. * @param onLoad defines an optional callback raised when the texture is loaded
  14939. * @param onError defines an optional callback raised if there is an issue to load the texture
  14940. * @param format defines the format of the data
  14941. * @param forcedExtension defines the extension to use to pick the right loader
  14942. * @returns the cube texture as an InternalTexture
  14943. */
  14944. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14945. var _this = this;
  14946. if (onLoad === void 0) { onLoad = null; }
  14947. if (onError === void 0) { onError = null; }
  14948. if (forcedExtension === void 0) { forcedExtension = null; }
  14949. var callback = function (loadData) {
  14950. if (!loadData) {
  14951. if (onLoad) {
  14952. onLoad(null);
  14953. }
  14954. return;
  14955. }
  14956. var texture = loadData.texture;
  14957. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14958. texture._lodGenerationScale = scale;
  14959. texture._lodGenerationOffset = offset;
  14960. if (_this._caps.textureLOD) {
  14961. // Do not add extra process if texture lod is supported.
  14962. if (onLoad) {
  14963. onLoad(texture);
  14964. }
  14965. return;
  14966. }
  14967. var mipSlices = 3;
  14968. var gl = _this._gl;
  14969. var width = loadData.width;
  14970. if (!width) {
  14971. return;
  14972. }
  14973. var textures = [];
  14974. for (var i = 0; i < mipSlices; i++) {
  14975. //compute LOD from even spacing in smoothness (matching shader calculation)
  14976. var smoothness = i / (mipSlices - 1);
  14977. var roughness = 1 - smoothness;
  14978. var minLODIndex = offset; // roughness = 0
  14979. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14980. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14981. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14982. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14983. glTextureFromLod.isCube = true;
  14984. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14989. if (loadData.isDDS) {
  14990. var info = loadData.info;
  14991. var data = loadData.data;
  14992. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14993. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14994. }
  14995. else {
  14996. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14997. }
  14998. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14999. // Wrap in a base texture for easy binding.
  15000. var lodTexture = new BABYLON.BaseTexture(scene);
  15001. lodTexture.isCube = true;
  15002. lodTexture._texture = glTextureFromLod;
  15003. glTextureFromLod.isReady = true;
  15004. textures.push(lodTexture);
  15005. }
  15006. texture._lodTextureHigh = textures[2];
  15007. texture._lodTextureMid = textures[1];
  15008. texture._lodTextureLow = textures[0];
  15009. if (onLoad) {
  15010. onLoad(texture);
  15011. }
  15012. };
  15013. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15014. };
  15015. /**
  15016. * Creates a cube texture
  15017. * @param rootUrl defines the url where the files to load is located
  15018. * @param scene defines the current scene
  15019. * @param files defines the list of files to load (1 per face)
  15020. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15021. * @param onLoad defines an optional callback raised when the texture is loaded
  15022. * @param onError defines an optional callback raised if there is an issue to load the texture
  15023. * @param format defines the format of the data
  15024. * @param forcedExtension defines the extension to use to pick the right loader
  15025. * @returns the cube texture as an InternalTexture
  15026. */
  15027. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15028. var _this = this;
  15029. if (onLoad === void 0) { onLoad = null; }
  15030. if (onError === void 0) { onError = null; }
  15031. if (forcedExtension === void 0) { forcedExtension = null; }
  15032. var gl = this._gl;
  15033. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15034. texture.isCube = true;
  15035. texture.url = rootUrl;
  15036. texture.generateMipMaps = !noMipmap;
  15037. if (!this._doNotHandleContextLost) {
  15038. texture._extension = forcedExtension;
  15039. texture._files = files;
  15040. }
  15041. var isKTX = false;
  15042. var isDDS = false;
  15043. var lastDot = rootUrl.lastIndexOf('.');
  15044. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15045. if (this._textureFormatInUse) {
  15046. extension = this._textureFormatInUse;
  15047. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15048. isKTX = true;
  15049. }
  15050. else {
  15051. isDDS = (extension === ".dds");
  15052. }
  15053. var onerror = function (request, exception) {
  15054. if (onError && request) {
  15055. onError(request.status + " " + request.statusText, exception);
  15056. }
  15057. };
  15058. if (isKTX) {
  15059. this._loadFile(rootUrl, function (data) {
  15060. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15061. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15062. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15063. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15064. ktx.uploadLevels(_this._gl, !noMipmap);
  15065. _this.setCubeMapTextureParams(gl, loadMipmap);
  15066. texture.width = ktx.pixelWidth;
  15067. texture.height = ktx.pixelHeight;
  15068. texture.isReady = true;
  15069. }, undefined, undefined, true, onerror);
  15070. }
  15071. else if (isDDS) {
  15072. if (files && files.length === 6) {
  15073. this._cascadeLoadFiles(scene, function (imgs) {
  15074. var info;
  15075. var loadMipmap = false;
  15076. var width = 0;
  15077. for (var index = 0; index < imgs.length; index++) {
  15078. var data = imgs[index];
  15079. info = BABYLON.DDSTools.GetDDSInfo(data);
  15080. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15081. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15082. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15083. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15084. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15085. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15086. }
  15087. texture.width = info.width;
  15088. texture.height = info.height;
  15089. texture.type = info.textureType;
  15090. width = info.width;
  15091. }
  15092. _this.setCubeMapTextureParams(gl, loadMipmap);
  15093. texture.isReady = true;
  15094. if (onLoad) {
  15095. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15096. }
  15097. }, files, onError);
  15098. }
  15099. else {
  15100. this._loadFile(rootUrl, function (data) {
  15101. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15102. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15103. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15104. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15105. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15106. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15107. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15108. }
  15109. _this.setCubeMapTextureParams(gl, loadMipmap);
  15110. texture.width = info.width;
  15111. texture.height = info.height;
  15112. texture.isReady = true;
  15113. texture.type = info.textureType;
  15114. if (onLoad) {
  15115. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15116. }
  15117. }, undefined, undefined, true, onerror);
  15118. }
  15119. }
  15120. else {
  15121. if (!files) {
  15122. throw new Error("Cannot load cubemap because files were not defined");
  15123. }
  15124. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15125. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15126. var height = width;
  15127. _this._prepareWorkingCanvas();
  15128. if (!_this._workingCanvas || !_this._workingContext) {
  15129. return;
  15130. }
  15131. _this._workingCanvas.width = width;
  15132. _this._workingCanvas.height = height;
  15133. var faces = [
  15134. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15135. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15136. ];
  15137. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15138. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15139. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15140. for (var index = 0; index < faces.length; index++) {
  15141. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15142. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15143. }
  15144. if (!noMipmap) {
  15145. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15146. }
  15147. _this.setCubeMapTextureParams(gl, !noMipmap);
  15148. texture.width = width;
  15149. texture.height = height;
  15150. texture.isReady = true;
  15151. if (format) {
  15152. texture.format = format;
  15153. }
  15154. texture.onLoadedObservable.notifyObservers(texture);
  15155. texture.onLoadedObservable.clear();
  15156. if (onLoad) {
  15157. onLoad();
  15158. }
  15159. }, files, onError);
  15160. }
  15161. this._internalTexturesCache.push(texture);
  15162. return texture;
  15163. };
  15164. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15166. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15167. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15169. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15170. // this.resetTextureCache();
  15171. };
  15172. /**
  15173. * Update a raw cube texture
  15174. * @param texture defines the texture to udpdate
  15175. * @param data defines the data to store
  15176. * @param format defines the data format
  15177. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15178. * @param invertY defines if data must be stored with Y axis inverted
  15179. * @param compression defines the compression used (null by default)
  15180. * @param level defines which level of the texture to update
  15181. */
  15182. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15183. if (compression === void 0) { compression = null; }
  15184. if (level === void 0) { level = 0; }
  15185. texture._bufferViewArray = data;
  15186. texture.format = format;
  15187. texture.type = type;
  15188. texture.invertY = invertY;
  15189. texture._compression = compression;
  15190. var gl = this._gl;
  15191. var textureType = this._getWebGLTextureType(type);
  15192. var internalFormat = this._getInternalFormat(format);
  15193. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15194. var needConversion = false;
  15195. if (internalFormat === gl.RGB) {
  15196. internalFormat = gl.RGBA;
  15197. needConversion = true;
  15198. }
  15199. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15200. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15201. if (texture.width % 4 !== 0) {
  15202. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15203. }
  15204. // Data are known to be in +X +Y +Z -X -Y -Z
  15205. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15206. var faceData = data[faceIndex];
  15207. if (compression) {
  15208. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15209. }
  15210. else {
  15211. if (needConversion) {
  15212. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15213. }
  15214. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15215. }
  15216. }
  15217. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15218. if (isPot && texture.generateMipMaps && level === 0) {
  15219. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15220. }
  15221. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15222. // this.resetTextureCache();
  15223. texture.isReady = true;
  15224. };
  15225. /**
  15226. * Creates a new raw cube texture
  15227. * @param data defines the array of data to use to create each face
  15228. * @param size defines the size of the textures
  15229. * @param format defines the format of the data
  15230. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15231. * @param generateMipMaps defines if the engine should generate the mip levels
  15232. * @param invertY defines if data must be stored with Y axis inverted
  15233. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15234. * @param compression defines the compression used (null by default)
  15235. * @returns the cube texture as an InternalTexture
  15236. */
  15237. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15238. if (compression === void 0) { compression = null; }
  15239. var gl = this._gl;
  15240. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15241. texture.isCube = true;
  15242. texture.generateMipMaps = generateMipMaps;
  15243. texture.format = format;
  15244. texture.type = type;
  15245. if (!this._doNotHandleContextLost) {
  15246. texture._bufferViewArray = data;
  15247. }
  15248. var textureType = this._getWebGLTextureType(type);
  15249. var internalFormat = this._getInternalFormat(format);
  15250. if (internalFormat === gl.RGB) {
  15251. internalFormat = gl.RGBA;
  15252. }
  15253. var width = size;
  15254. var height = width;
  15255. texture.width = width;
  15256. texture.height = height;
  15257. // Double check on POT to generate Mips.
  15258. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15259. if (!isPot) {
  15260. generateMipMaps = false;
  15261. }
  15262. // Upload data if needed. The texture won't be ready until then.
  15263. if (data) {
  15264. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15265. }
  15266. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15267. // Filters
  15268. if (data && generateMipMaps) {
  15269. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15270. }
  15271. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15274. }
  15275. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15276. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15278. }
  15279. else {
  15280. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15283. }
  15284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15286. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15287. return texture;
  15288. };
  15289. /**
  15290. * Creates a new raw cube texture from a specified url
  15291. * @param url defines the url where the data is located
  15292. * @param scene defines the current scene
  15293. * @param size defines the size of the textures
  15294. * @param format defines the format of the data
  15295. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15296. * @param noMipmap defines if the engine should avoid generating the mip levels
  15297. * @param callback defines a callback used to extract texture data from loaded data
  15298. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15299. * @param onLoad defines a callback called when texture is loaded
  15300. * @param onError defines a callback called if there is an error
  15301. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15302. * @param invertY defines if data must be stored with Y axis inverted
  15303. * @returns the cube texture as an InternalTexture
  15304. */
  15305. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15306. var _this = this;
  15307. if (onLoad === void 0) { onLoad = null; }
  15308. if (onError === void 0) { onError = null; }
  15309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15310. if (invertY === void 0) { invertY = false; }
  15311. var gl = this._gl;
  15312. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15313. scene._addPendingData(texture);
  15314. texture.url = url;
  15315. this._internalTexturesCache.push(texture);
  15316. var onerror = function (request, exception) {
  15317. scene._removePendingData(texture);
  15318. if (onError && request) {
  15319. onError(request.status + " " + request.statusText, exception);
  15320. }
  15321. };
  15322. var internalCallback = function (data) {
  15323. var width = texture.width;
  15324. var faceDataArrays = callback(data);
  15325. if (!faceDataArrays) {
  15326. return;
  15327. }
  15328. if (mipmapGenerator) {
  15329. var textureType = _this._getWebGLTextureType(type);
  15330. var internalFormat = _this._getInternalFormat(format);
  15331. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15332. var needConversion = false;
  15333. if (internalFormat === gl.RGB) {
  15334. internalFormat = gl.RGBA;
  15335. needConversion = true;
  15336. }
  15337. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15338. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15339. var mipData = mipmapGenerator(faceDataArrays);
  15340. for (var level = 0; level < mipData.length; level++) {
  15341. var mipSize = width >> level;
  15342. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15343. var mipFaceData = mipData[level][faceIndex];
  15344. if (needConversion) {
  15345. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15346. }
  15347. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15348. }
  15349. }
  15350. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15351. }
  15352. else {
  15353. texture.generateMipMaps = !noMipmap;
  15354. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15355. }
  15356. texture.isReady = true;
  15357. // this.resetTextureCache();
  15358. scene._removePendingData(texture);
  15359. if (onLoad) {
  15360. onLoad();
  15361. }
  15362. };
  15363. this._loadFile(url, function (data) {
  15364. internalCallback(data);
  15365. }, undefined, scene.database, true, onerror);
  15366. return texture;
  15367. };
  15368. ;
  15369. /**
  15370. * Update a raw 3D texture
  15371. * @param texture defines the texture to update
  15372. * @param data defines the data to store
  15373. * @param format defines the data format
  15374. * @param invertY defines if data must be stored with Y axis inverted
  15375. * @param compression defines the used compression (can be null)
  15376. */
  15377. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15378. if (compression === void 0) { compression = null; }
  15379. var internalFormat = this._getInternalFormat(format);
  15380. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15381. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15382. if (!this._doNotHandleContextLost) {
  15383. texture._bufferView = data;
  15384. texture.format = format;
  15385. texture.invertY = invertY;
  15386. texture._compression = compression;
  15387. }
  15388. if (texture.width % 4 !== 0) {
  15389. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15390. }
  15391. if (compression && data) {
  15392. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15393. }
  15394. else {
  15395. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15396. }
  15397. if (texture.generateMipMaps) {
  15398. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15399. }
  15400. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15401. // this.resetTextureCache();
  15402. texture.isReady = true;
  15403. };
  15404. /**
  15405. * Creates a new raw 3D texture
  15406. * @param data defines the data used to create the texture
  15407. * @param width defines the width of the texture
  15408. * @param height defines the height of the texture
  15409. * @param depth defines the depth of the texture
  15410. * @param format defines the format of the texture
  15411. * @param generateMipMaps defines if the engine must generate mip levels
  15412. * @param invertY defines if data must be stored with Y axis inverted
  15413. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15414. * @param compression defines the compressed used (can be null)
  15415. * @returns a new raw 3D texture (stored in an InternalTexture)
  15416. */
  15417. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15418. if (compression === void 0) { compression = null; }
  15419. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15420. texture.baseWidth = width;
  15421. texture.baseHeight = height;
  15422. texture.baseDepth = depth;
  15423. texture.width = width;
  15424. texture.height = height;
  15425. texture.depth = depth;
  15426. texture.format = format;
  15427. texture.generateMipMaps = generateMipMaps;
  15428. texture.samplingMode = samplingMode;
  15429. texture.is3D = true;
  15430. if (!this._doNotHandleContextLost) {
  15431. texture._bufferView = data;
  15432. }
  15433. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15434. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15435. // Filters
  15436. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15437. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15438. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15439. if (generateMipMaps) {
  15440. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15441. }
  15442. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15443. this._internalTexturesCache.push(texture);
  15444. return texture;
  15445. };
  15446. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15447. var gl = this._gl;
  15448. if (!gl) {
  15449. return;
  15450. }
  15451. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15454. if (!noMipmap && !isCompressed) {
  15455. gl.generateMipmap(gl.TEXTURE_2D);
  15456. }
  15457. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15458. // this.resetTextureCache();
  15459. if (scene) {
  15460. scene._removePendingData(texture);
  15461. }
  15462. texture.onLoadedObservable.notifyObservers(texture);
  15463. texture.onLoadedObservable.clear();
  15464. };
  15465. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15466. var _this = this;
  15467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15468. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15469. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15470. var gl = this._gl;
  15471. if (!gl) {
  15472. return;
  15473. }
  15474. if (!texture._webGLTexture) {
  15475. // this.resetTextureCache();
  15476. if (scene) {
  15477. scene._removePendingData(texture);
  15478. }
  15479. return;
  15480. }
  15481. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15482. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15483. texture.baseWidth = width;
  15484. texture.baseHeight = height;
  15485. texture.width = potWidth;
  15486. texture.height = potHeight;
  15487. texture.isReady = true;
  15488. if (processFunction(potWidth, potHeight, function () {
  15489. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15490. })) {
  15491. // Returning as texture needs extra async steps
  15492. return;
  15493. }
  15494. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15495. };
  15496. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15497. // Create new RGBA data container.
  15498. var rgbaData;
  15499. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15500. rgbaData = new Float32Array(width * height * 4);
  15501. }
  15502. else {
  15503. rgbaData = new Uint32Array(width * height * 4);
  15504. }
  15505. // Convert each pixel.
  15506. for (var x = 0; x < width; x++) {
  15507. for (var y = 0; y < height; y++) {
  15508. var index = (y * width + x) * 3;
  15509. var newIndex = (y * width + x) * 4;
  15510. // Map Old Value to new value.
  15511. rgbaData[newIndex + 0] = rgbData[index + 0];
  15512. rgbaData[newIndex + 1] = rgbData[index + 1];
  15513. rgbaData[newIndex + 2] = rgbData[index + 2];
  15514. // Add fully opaque alpha channel.
  15515. rgbaData[newIndex + 3] = 1;
  15516. }
  15517. }
  15518. return rgbaData;
  15519. };
  15520. /** @ignore */
  15521. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15522. var gl = this._gl;
  15523. if (texture._framebuffer) {
  15524. gl.deleteFramebuffer(texture._framebuffer);
  15525. texture._framebuffer = null;
  15526. }
  15527. if (texture._depthStencilBuffer) {
  15528. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15529. texture._depthStencilBuffer = null;
  15530. }
  15531. if (texture._MSAAFramebuffer) {
  15532. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15533. texture._MSAAFramebuffer = null;
  15534. }
  15535. if (texture._MSAARenderBuffer) {
  15536. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15537. texture._MSAARenderBuffer = null;
  15538. }
  15539. };
  15540. /** @ignore */
  15541. Engine.prototype._releaseTexture = function (texture) {
  15542. var gl = this._gl;
  15543. this._releaseFramebufferObjects(texture);
  15544. gl.deleteTexture(texture._webGLTexture);
  15545. // Unbind channels
  15546. this.unbindAllTextures();
  15547. var index = this._internalTexturesCache.indexOf(texture);
  15548. if (index !== -1) {
  15549. this._internalTexturesCache.splice(index, 1);
  15550. }
  15551. // Integrated fixed lod samplers.
  15552. if (texture._lodTextureHigh) {
  15553. texture._lodTextureHigh.dispose();
  15554. }
  15555. if (texture._lodTextureMid) {
  15556. texture._lodTextureMid.dispose();
  15557. }
  15558. if (texture._lodTextureLow) {
  15559. texture._lodTextureLow.dispose();
  15560. }
  15561. // Set output texture of post process to null if the texture has been released/disposed
  15562. this.scenes.forEach(function (scene) {
  15563. scene.postProcesses.forEach(function (postProcess) {
  15564. if (postProcess._outputTexture == texture) {
  15565. postProcess._outputTexture = null;
  15566. }
  15567. });
  15568. scene.cameras.forEach(function (camera) {
  15569. camera._postProcesses.forEach(function (postProcess) {
  15570. if (postProcess) {
  15571. if (postProcess._outputTexture == texture) {
  15572. postProcess._outputTexture = null;
  15573. }
  15574. }
  15575. });
  15576. });
  15577. });
  15578. };
  15579. Engine.prototype.setProgram = function (program) {
  15580. if (this._currentProgram !== program) {
  15581. this._gl.useProgram(program);
  15582. this._currentProgram = program;
  15583. }
  15584. };
  15585. /**
  15586. * Binds an effect to the webGL context
  15587. * @param effect defines the effect to bind
  15588. */
  15589. Engine.prototype.bindSamplers = function (effect) {
  15590. this.setProgram(effect.getProgram());
  15591. var samplers = effect.getSamplers();
  15592. for (var index = 0; index < samplers.length; index++) {
  15593. var uniform = effect.getUniform(samplers[index]);
  15594. if (uniform) {
  15595. this._boundUniforms[index] = uniform;
  15596. }
  15597. }
  15598. this._currentEffect = null;
  15599. };
  15600. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15601. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15602. return;
  15603. }
  15604. // Remove
  15605. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15606. // Bind last to it
  15607. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15608. // Bind to dummy
  15609. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15610. };
  15611. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15612. if (!internalTexture) {
  15613. return -1;
  15614. }
  15615. internalTexture._initialSlot = channel;
  15616. if (this.disableTextureBindingOptimization) {
  15617. if (channel !== internalTexture._designatedSlot) {
  15618. this._textureCollisions.addCount(1, false);
  15619. }
  15620. }
  15621. else {
  15622. if (channel !== internalTexture._designatedSlot) {
  15623. if (internalTexture._designatedSlot > -1) {
  15624. return internalTexture._designatedSlot;
  15625. }
  15626. else {
  15627. // No slot for this texture, let's pick a new one (if we find a free slot)
  15628. if (this._nextFreeTextureSlots.length) {
  15629. return this._nextFreeTextureSlots[0];
  15630. }
  15631. // We need to recycle the oldest bound texture, sorry.
  15632. this._textureCollisions.addCount(1, false);
  15633. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15634. }
  15635. }
  15636. }
  15637. return channel;
  15638. };
  15639. Engine.prototype._linkTrackers = function (previous, next) {
  15640. previous.next = next;
  15641. next.previous = previous;
  15642. };
  15643. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15644. var currentSlot = internalTexture._designatedSlot;
  15645. if (currentSlot === -1) {
  15646. return -1;
  15647. }
  15648. internalTexture._designatedSlot = -1;
  15649. if (this.disableTextureBindingOptimization) {
  15650. return -1;
  15651. }
  15652. // Remove from bound list
  15653. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15654. // Free the slot
  15655. this._boundTexturesCache[currentSlot] = null;
  15656. this._nextFreeTextureSlots.push(currentSlot);
  15657. return currentSlot;
  15658. };
  15659. Engine.prototype._activateCurrentTexture = function () {
  15660. if (this._currentTextureChannel !== this._activeChannel) {
  15661. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15662. this._currentTextureChannel = this._activeChannel;
  15663. }
  15664. };
  15665. /** @ignore */
  15666. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  15667. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15668. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15669. this._activeChannel = texture._designatedSlot;
  15670. }
  15671. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15672. var isTextureForRendering = texture && texture._initialSlot > -1;
  15673. if (currentTextureBound !== texture) {
  15674. if (currentTextureBound) {
  15675. this._removeDesignatedSlot(currentTextureBound);
  15676. }
  15677. this._activateCurrentTexture();
  15678. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15679. this._boundTexturesCache[this._activeChannel] = texture;
  15680. if (texture) {
  15681. if (!this.disableTextureBindingOptimization) {
  15682. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15683. if (slotIndex > -1) {
  15684. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15685. }
  15686. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15687. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15688. }
  15689. texture._designatedSlot = this._activeChannel;
  15690. }
  15691. }
  15692. else if (forTextureDataUpdate) {
  15693. this._activateCurrentTexture();
  15694. }
  15695. if (isTextureForRendering && !forTextureDataUpdate) {
  15696. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  15697. }
  15698. };
  15699. /** @ignore */
  15700. Engine.prototype._bindTexture = function (channel, texture) {
  15701. if (channel < 0) {
  15702. return;
  15703. }
  15704. if (texture) {
  15705. channel = this._getCorrectTextureChannel(channel, texture);
  15706. }
  15707. this._activeChannel = channel;
  15708. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  15709. };
  15710. /**
  15711. * Sets a texture to the webGL context from a postprocess
  15712. * @param channel defines the channel to use
  15713. * @param postProcess defines the source postprocess
  15714. */
  15715. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  15716. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  15717. };
  15718. /**
  15719. * Binds the output of the passed in post process to the texture channel specified
  15720. * @param channel The channel the texture should be bound to
  15721. * @param postProcess The post process which's output should be bound
  15722. */
  15723. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  15724. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  15725. };
  15726. /**
  15727. * Unbind all textures from the webGL context
  15728. */
  15729. Engine.prototype.unbindAllTextures = function () {
  15730. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  15731. this._activeChannel = channel;
  15732. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15733. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15734. if (this.webGLVersion > 1) {
  15735. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15736. }
  15737. }
  15738. };
  15739. /**
  15740. * Sets a texture to the according uniform.
  15741. * @param channel The texture channel
  15742. * @param uniform The uniform to set
  15743. * @param texture The texture to apply
  15744. */
  15745. Engine.prototype.setTexture = function (channel, uniform, texture) {
  15746. if (channel < 0) {
  15747. return;
  15748. }
  15749. if (uniform) {
  15750. this._boundUniforms[channel] = uniform;
  15751. }
  15752. this._setTexture(channel, texture);
  15753. };
  15754. /**
  15755. * Sets a depth stencil texture from a render target to the according uniform.
  15756. * @param channel The texture channel
  15757. * @param uniform The uniform to set
  15758. * @param texture The render target texture containing the depth stencil texture to apply
  15759. */
  15760. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  15761. if (channel < 0) {
  15762. return;
  15763. }
  15764. if (uniform) {
  15765. this._boundUniforms[channel] = uniform;
  15766. }
  15767. if (!texture || !texture.depthStencilTexture) {
  15768. this._setTexture(channel, null);
  15769. }
  15770. else {
  15771. this._setTexture(channel, texture, false, true);
  15772. }
  15773. };
  15774. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  15775. var uniform = this._boundUniforms[sourceSlot];
  15776. if (uniform._currentState === destination) {
  15777. return;
  15778. }
  15779. this._gl.uniform1i(uniform, destination);
  15780. uniform._currentState = destination;
  15781. };
  15782. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  15783. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  15784. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  15785. // Not ready?
  15786. if (!texture) {
  15787. if (this._boundTexturesCache[channel] != null) {
  15788. this._activeChannel = channel;
  15789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15790. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15791. if (this.webGLVersion > 1) {
  15792. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15793. }
  15794. }
  15795. return false;
  15796. }
  15797. // Video
  15798. if (texture.video) {
  15799. this._activeChannel = channel;
  15800. texture.update();
  15801. }
  15802. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  15803. texture.delayLoad();
  15804. return false;
  15805. }
  15806. var internalTexture;
  15807. if (depthStencilTexture) {
  15808. internalTexture = texture.depthStencilTexture;
  15809. }
  15810. else if (texture.isReady()) {
  15811. internalTexture = texture.getInternalTexture();
  15812. }
  15813. else if (texture.isCube) {
  15814. internalTexture = this.emptyCubeTexture;
  15815. }
  15816. else if (texture.is3D) {
  15817. internalTexture = this.emptyTexture3D;
  15818. }
  15819. else {
  15820. internalTexture = this.emptyTexture;
  15821. }
  15822. if (!isPartOfTextureArray) {
  15823. channel = this._getCorrectTextureChannel(channel, internalTexture);
  15824. }
  15825. if (this._boundTexturesCache[channel] === internalTexture) {
  15826. this._moveBoundTextureOnTop(internalTexture);
  15827. if (!isPartOfTextureArray) {
  15828. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  15829. }
  15830. return false;
  15831. }
  15832. this._activeChannel = channel;
  15833. if (internalTexture && internalTexture.is3D) {
  15834. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  15835. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  15836. internalTexture._cachedWrapU = texture.wrapU;
  15837. switch (texture.wrapU) {
  15838. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15839. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  15840. break;
  15841. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  15843. break;
  15844. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15845. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  15846. break;
  15847. }
  15848. }
  15849. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  15850. internalTexture._cachedWrapV = texture.wrapV;
  15851. switch (texture.wrapV) {
  15852. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15853. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  15854. break;
  15855. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15856. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  15857. break;
  15858. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15859. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  15860. break;
  15861. }
  15862. }
  15863. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  15864. internalTexture._cachedWrapR = texture.wrapR;
  15865. switch (texture.wrapR) {
  15866. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15867. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  15868. break;
  15869. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15870. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  15871. break;
  15872. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15873. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  15874. break;
  15875. }
  15876. }
  15877. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  15878. }
  15879. else if (internalTexture && internalTexture.isCube) {
  15880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  15881. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  15882. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  15883. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  15884. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  15885. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  15886. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  15887. }
  15888. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  15889. }
  15890. else {
  15891. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  15892. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  15893. internalTexture._cachedWrapU = texture.wrapU;
  15894. switch (texture.wrapU) {
  15895. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  15897. break;
  15898. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  15900. break;
  15901. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15902. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  15903. break;
  15904. }
  15905. }
  15906. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  15907. internalTexture._cachedWrapV = texture.wrapV;
  15908. switch (texture.wrapV) {
  15909. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  15911. break;
  15912. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  15914. break;
  15915. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15916. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  15917. break;
  15918. }
  15919. }
  15920. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  15921. }
  15922. return true;
  15923. };
  15924. /**
  15925. * Sets an array of texture to the webGL context
  15926. * @param channel defines the channel where the texture array must be set
  15927. * @param uniform defines the associated uniform location
  15928. * @param textures defines the array of textures to bind
  15929. */
  15930. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  15931. if (channel < 0 || !uniform) {
  15932. return;
  15933. }
  15934. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  15935. this._textureUnits = new Int32Array(textures.length);
  15936. }
  15937. for (var i = 0; i < textures.length; i++) {
  15938. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  15939. }
  15940. this._gl.uniform1iv(uniform, this._textureUnits);
  15941. for (var index = 0; index < textures.length; index++) {
  15942. this._setTexture(this._textureUnits[index], textures[index], true);
  15943. }
  15944. };
  15945. /** @ignore */
  15946. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  15947. var internalTexture = texture.getInternalTexture();
  15948. if (!internalTexture) {
  15949. return;
  15950. }
  15951. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  15952. var value = texture.anisotropicFilteringLevel;
  15953. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  15954. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  15955. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  15956. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  15957. }
  15958. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  15959. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  15960. internalTexture._cachedAnisotropicFilteringLevel = value;
  15961. }
  15962. };
  15963. /**
  15964. * Reads pixels from the current frame buffer. Please note that this function can be slow
  15965. * @param x defines the x coordinate of the rectangle where pixels must be read
  15966. * @param y defines the y coordinate of the rectangle where pixels must be read
  15967. * @param width defines the width of the rectangle where pixels must be read
  15968. * @param height defines the height of the rectangle where pixels must be read
  15969. * @returns a Uint8Array containing RGBA colors
  15970. */
  15971. Engine.prototype.readPixels = function (x, y, width, height) {
  15972. var data = new Uint8Array(height * width * 4);
  15973. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  15974. return data;
  15975. };
  15976. /**
  15977. * Add an externaly attached data from its key.
  15978. * This method call will fail and return false, if such key already exists.
  15979. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15980. * @param key the unique key that identifies the data
  15981. * @param data the data object to associate to the key for this Engine instance
  15982. * @return true if no such key were already present and the data was added successfully, false otherwise
  15983. */
  15984. Engine.prototype.addExternalData = function (key, data) {
  15985. if (!this._externalData) {
  15986. this._externalData = new BABYLON.StringDictionary();
  15987. }
  15988. return this._externalData.add(key, data);
  15989. };
  15990. /**
  15991. * Get an externaly attached data from its key
  15992. * @param key the unique key that identifies the data
  15993. * @return the associated data, if present (can be null), or undefined if not present
  15994. */
  15995. Engine.prototype.getExternalData = function (key) {
  15996. if (!this._externalData) {
  15997. this._externalData = new BABYLON.StringDictionary();
  15998. }
  15999. return this._externalData.get(key);
  16000. };
  16001. /**
  16002. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16003. * @param key the unique key that identifies the data
  16004. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16005. * @return the associated data, can be null if the factory returned null.
  16006. */
  16007. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16008. if (!this._externalData) {
  16009. this._externalData = new BABYLON.StringDictionary();
  16010. }
  16011. return this._externalData.getOrAddWithFactory(key, factory);
  16012. };
  16013. /**
  16014. * Remove an externaly attached data from the Engine instance
  16015. * @param key the unique key that identifies the data
  16016. * @return true if the data was successfully removed, false if it doesn't exist
  16017. */
  16018. Engine.prototype.removeExternalData = function (key) {
  16019. if (!this._externalData) {
  16020. this._externalData = new BABYLON.StringDictionary();
  16021. }
  16022. return this._externalData.remove(key);
  16023. };
  16024. /**
  16025. * Unbind all vertex attributes from the webGL context
  16026. */
  16027. Engine.prototype.unbindAllAttributes = function () {
  16028. if (this._mustWipeVertexAttributes) {
  16029. this._mustWipeVertexAttributes = false;
  16030. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16031. this._gl.disableVertexAttribArray(i);
  16032. this._vertexAttribArraysEnabled[i] = false;
  16033. this._currentBufferPointers[i].active = false;
  16034. }
  16035. return;
  16036. }
  16037. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16038. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16039. continue;
  16040. }
  16041. this._gl.disableVertexAttribArray(i);
  16042. this._vertexAttribArraysEnabled[i] = false;
  16043. this._currentBufferPointers[i].active = false;
  16044. }
  16045. };
  16046. /**
  16047. * 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
  16048. */
  16049. Engine.prototype.releaseEffects = function () {
  16050. for (var name in this._compiledEffects) {
  16051. this._deleteProgram(this._compiledEffects[name]._program);
  16052. }
  16053. this._compiledEffects = {};
  16054. };
  16055. /**
  16056. * Dispose and release all associated resources
  16057. */
  16058. Engine.prototype.dispose = function () {
  16059. this.hideLoadingUI();
  16060. this.stopRenderLoop();
  16061. // Release postProcesses
  16062. while (this.postProcesses.length) {
  16063. this.postProcesses[0].dispose();
  16064. }
  16065. // Empty texture
  16066. if (this._emptyTexture) {
  16067. this._releaseTexture(this._emptyTexture);
  16068. this._emptyTexture = null;
  16069. }
  16070. if (this._emptyCubeTexture) {
  16071. this._releaseTexture(this._emptyCubeTexture);
  16072. this._emptyCubeTexture = null;
  16073. }
  16074. // Rescale PP
  16075. if (this._rescalePostProcess) {
  16076. this._rescalePostProcess.dispose();
  16077. }
  16078. // Release scenes
  16079. while (this.scenes.length) {
  16080. this.scenes[0].dispose();
  16081. }
  16082. // Release audio engine
  16083. if (Engine.audioEngine) {
  16084. Engine.audioEngine.dispose();
  16085. }
  16086. // Release effects
  16087. this.releaseEffects();
  16088. // Unbind
  16089. this.unbindAllAttributes();
  16090. this._boundUniforms = [];
  16091. if (this._dummyFramebuffer) {
  16092. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16093. }
  16094. //WebVR
  16095. this.disableVR();
  16096. // Events
  16097. if (BABYLON.Tools.IsWindowObjectExist()) {
  16098. window.removeEventListener("blur", this._onBlur);
  16099. window.removeEventListener("focus", this._onFocus);
  16100. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16101. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16102. if (this._renderingCanvas) {
  16103. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16104. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16105. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16106. if (!this._doNotHandleContextLost) {
  16107. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16108. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16109. }
  16110. }
  16111. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16112. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16113. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16114. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16115. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16116. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16117. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16118. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16119. if (this._onVrDisplayConnect) {
  16120. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16121. if (this._onVrDisplayDisconnect) {
  16122. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16123. }
  16124. if (this._onVrDisplayPresentChange) {
  16125. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16126. }
  16127. this._onVrDisplayConnect = null;
  16128. this._onVrDisplayDisconnect = null;
  16129. }
  16130. }
  16131. // Remove from Instances
  16132. var index = Engine.Instances.indexOf(this);
  16133. if (index >= 0) {
  16134. Engine.Instances.splice(index, 1);
  16135. }
  16136. this._workingCanvas = null;
  16137. this._workingContext = null;
  16138. this._currentBufferPointers = [];
  16139. this._renderingCanvas = null;
  16140. this._currentProgram = null;
  16141. this._bindedRenderFunction = null;
  16142. this.onResizeObservable.clear();
  16143. this.onCanvasBlurObservable.clear();
  16144. this.onCanvasFocusObservable.clear();
  16145. this.onCanvasPointerOutObservable.clear();
  16146. this.onBeginFrameObservable.clear();
  16147. this.onEndFrameObservable.clear();
  16148. BABYLON.Effect.ResetCache();
  16149. // Abort active requests
  16150. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16151. var request = _a[_i];
  16152. request.abort();
  16153. }
  16154. };
  16155. // Loading screen
  16156. /**
  16157. * Display the loading screen
  16158. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16159. */
  16160. Engine.prototype.displayLoadingUI = function () {
  16161. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16162. return;
  16163. }
  16164. var loadingScreen = this.loadingScreen;
  16165. if (loadingScreen) {
  16166. loadingScreen.displayLoadingUI();
  16167. }
  16168. };
  16169. /**
  16170. * Hide the loading screen
  16171. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16172. */
  16173. Engine.prototype.hideLoadingUI = function () {
  16174. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16175. return;
  16176. }
  16177. var loadingScreen = this.loadingScreen;
  16178. if (loadingScreen) {
  16179. loadingScreen.hideLoadingUI();
  16180. }
  16181. };
  16182. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16183. /**
  16184. * Gets the current loading screen object
  16185. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16186. */
  16187. get: function () {
  16188. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16189. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16190. return this._loadingScreen;
  16191. },
  16192. /**
  16193. * Sets the current loading screen object
  16194. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16195. */
  16196. set: function (loadingScreen) {
  16197. this._loadingScreen = loadingScreen;
  16198. },
  16199. enumerable: true,
  16200. configurable: true
  16201. });
  16202. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16203. /**
  16204. * Sets the current loading screen text
  16205. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16206. */
  16207. set: function (text) {
  16208. this.loadingScreen.loadingUIText = text;
  16209. },
  16210. enumerable: true,
  16211. configurable: true
  16212. });
  16213. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16214. /**
  16215. * Sets the current loading screen background color
  16216. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16217. */
  16218. set: function (color) {
  16219. this.loadingScreen.loadingUIBackgroundColor = color;
  16220. },
  16221. enumerable: true,
  16222. configurable: true
  16223. });
  16224. /**
  16225. * Attach a new callback raised when context lost event is fired
  16226. * @param callback defines the callback to call
  16227. */
  16228. Engine.prototype.attachContextLostEvent = function (callback) {
  16229. if (this._renderingCanvas) {
  16230. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16231. }
  16232. };
  16233. /**
  16234. * Attach a new callback raised when context restored event is fired
  16235. * @param callback defines the callback to call
  16236. */
  16237. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16238. if (this._renderingCanvas) {
  16239. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16240. }
  16241. };
  16242. /**
  16243. * Gets the source code of the vertex shader associated with a specific webGL program
  16244. * @param program defines the program to use
  16245. * @returns a string containing the source code of the vertex shader associated with the program
  16246. */
  16247. Engine.prototype.getVertexShaderSource = function (program) {
  16248. var shaders = this._gl.getAttachedShaders(program);
  16249. if (!shaders) {
  16250. return null;
  16251. }
  16252. return this._gl.getShaderSource(shaders[0]);
  16253. };
  16254. /**
  16255. * Gets the source code of the fragment shader associated with a specific webGL program
  16256. * @param program defines the program to use
  16257. * @returns a string containing the source code of the fragment shader associated with the program
  16258. */
  16259. Engine.prototype.getFragmentShaderSource = function (program) {
  16260. var shaders = this._gl.getAttachedShaders(program);
  16261. if (!shaders) {
  16262. return null;
  16263. }
  16264. return this._gl.getShaderSource(shaders[1]);
  16265. };
  16266. /**
  16267. * Get the current error code of the webGL context
  16268. * @returns the error code
  16269. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16270. */
  16271. Engine.prototype.getError = function () {
  16272. return this._gl.getError();
  16273. };
  16274. // FPS
  16275. /**
  16276. * Gets the current framerate
  16277. * @returns a number representing the framerate
  16278. */
  16279. Engine.prototype.getFps = function () {
  16280. return this._fps;
  16281. };
  16282. /**
  16283. * Gets the time spent between current and previous frame
  16284. * @returns a number representing the delta time in ms
  16285. */
  16286. Engine.prototype.getDeltaTime = function () {
  16287. return this._deltaTime;
  16288. };
  16289. Engine.prototype._measureFps = function () {
  16290. this._performanceMonitor.sampleFrame();
  16291. this._fps = this._performanceMonitor.averageFPS;
  16292. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16293. };
  16294. /** @ignore */
  16295. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16296. if (faceIndex === void 0) { faceIndex = -1; }
  16297. var gl = this._gl;
  16298. if (!this._dummyFramebuffer) {
  16299. var dummy = gl.createFramebuffer();
  16300. if (!dummy) {
  16301. throw new Error("Unable to create dummy framebuffer");
  16302. }
  16303. this._dummyFramebuffer = dummy;
  16304. }
  16305. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16306. if (faceIndex > -1) {
  16307. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16308. }
  16309. else {
  16310. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16311. }
  16312. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16313. var buffer;
  16314. switch (readType) {
  16315. case gl.UNSIGNED_BYTE:
  16316. buffer = new Uint8Array(4 * width * height);
  16317. readType = gl.UNSIGNED_BYTE;
  16318. break;
  16319. default:
  16320. buffer = new Float32Array(4 * width * height);
  16321. readType = gl.FLOAT;
  16322. break;
  16323. }
  16324. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16325. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16326. return buffer;
  16327. };
  16328. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16329. if (this._webGLVersion > 1) {
  16330. return this._caps.colorBufferFloat;
  16331. }
  16332. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16333. };
  16334. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16335. if (this._webGLVersion > 1) {
  16336. return this._caps.colorBufferFloat;
  16337. }
  16338. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16339. };
  16340. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16341. Engine.prototype._canRenderToFramebuffer = function (type) {
  16342. var gl = this._gl;
  16343. //clear existing errors
  16344. while (gl.getError() !== gl.NO_ERROR) { }
  16345. var successful = true;
  16346. var texture = gl.createTexture();
  16347. gl.bindTexture(gl.TEXTURE_2D, texture);
  16348. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16351. var fb = gl.createFramebuffer();
  16352. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16353. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16354. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16355. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16356. successful = successful && (gl.getError() === gl.NO_ERROR);
  16357. //try render by clearing frame buffer's color buffer
  16358. if (successful) {
  16359. gl.clear(gl.COLOR_BUFFER_BIT);
  16360. successful = successful && (gl.getError() === gl.NO_ERROR);
  16361. }
  16362. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16363. if (successful) {
  16364. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16365. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16366. var readFormat = gl.RGBA;
  16367. var readType = gl.UNSIGNED_BYTE;
  16368. var buffer = new Uint8Array(4);
  16369. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16370. successful = successful && (gl.getError() === gl.NO_ERROR);
  16371. }
  16372. //clean up
  16373. gl.deleteTexture(texture);
  16374. gl.deleteFramebuffer(fb);
  16375. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16376. //clear accumulated errors
  16377. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16378. return successful;
  16379. };
  16380. /** @ignore */
  16381. Engine.prototype._getWebGLTextureType = function (type) {
  16382. if (type === Engine.TEXTURETYPE_FLOAT) {
  16383. return this._gl.FLOAT;
  16384. }
  16385. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16386. // Add Half Float Constant.
  16387. return this._gl.HALF_FLOAT_OES;
  16388. }
  16389. return this._gl.UNSIGNED_BYTE;
  16390. };
  16391. ;
  16392. Engine.prototype._getInternalFormat = function (format) {
  16393. var internalFormat = this._gl.RGBA;
  16394. switch (format) {
  16395. case Engine.TEXTUREFORMAT_ALPHA:
  16396. internalFormat = this._gl.ALPHA;
  16397. break;
  16398. case Engine.TEXTUREFORMAT_LUMINANCE:
  16399. internalFormat = this._gl.LUMINANCE;
  16400. break;
  16401. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16402. internalFormat = this._gl.LUMINANCE_ALPHA;
  16403. break;
  16404. case Engine.TEXTUREFORMAT_RGB:
  16405. case Engine.TEXTUREFORMAT_RGB32F:
  16406. internalFormat = this._gl.RGB;
  16407. break;
  16408. case Engine.TEXTUREFORMAT_RGBA:
  16409. case Engine.TEXTUREFORMAT_RGBA32F:
  16410. internalFormat = this._gl.RGBA;
  16411. break;
  16412. case Engine.TEXTUREFORMAT_R32F:
  16413. internalFormat = this._gl.RED;
  16414. break;
  16415. case Engine.TEXTUREFORMAT_RG32F:
  16416. internalFormat = this._gl.RG;
  16417. break;
  16418. }
  16419. return internalFormat;
  16420. };
  16421. /** @ignore */
  16422. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16423. if (this._webGLVersion === 1) {
  16424. if (format) {
  16425. switch (format) {
  16426. case Engine.TEXTUREFORMAT_LUMINANCE:
  16427. return this._gl.LUMINANCE;
  16428. }
  16429. }
  16430. return this._gl.RGBA;
  16431. }
  16432. if (type === Engine.TEXTURETYPE_FLOAT) {
  16433. if (format) {
  16434. switch (format) {
  16435. case Engine.TEXTUREFORMAT_R32F:
  16436. return this._gl.R32F;
  16437. case Engine.TEXTUREFORMAT_RG32F:
  16438. return this._gl.RG32F;
  16439. case Engine.TEXTUREFORMAT_RGB32F:
  16440. return this._gl.RGB32F;
  16441. }
  16442. }
  16443. return this._gl.RGBA32F;
  16444. }
  16445. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16446. return this._gl.RGBA16F;
  16447. }
  16448. if (format) {
  16449. switch (format) {
  16450. case Engine.TEXTUREFORMAT_LUMINANCE:
  16451. return this._gl.LUMINANCE;
  16452. }
  16453. }
  16454. return this._gl.RGBA;
  16455. };
  16456. ;
  16457. /** @ignore */
  16458. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16459. if (type === Engine.TEXTURETYPE_FLOAT) {
  16460. return this._gl.RGBA32F;
  16461. }
  16462. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16463. return this._gl.RGBA16F;
  16464. }
  16465. return this._gl.RGBA8;
  16466. };
  16467. ;
  16468. /**
  16469. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16470. * @return the new query
  16471. */
  16472. Engine.prototype.createQuery = function () {
  16473. return this._gl.createQuery();
  16474. };
  16475. /**
  16476. * Delete and release a webGL query
  16477. * @param query defines the query to delete
  16478. * @return the current engine
  16479. */
  16480. Engine.prototype.deleteQuery = function (query) {
  16481. this._gl.deleteQuery(query);
  16482. return this;
  16483. };
  16484. /**
  16485. * Check if a given query has resolved and got its value
  16486. * @param query defines the query to check
  16487. * @returns true if the query got its value
  16488. */
  16489. Engine.prototype.isQueryResultAvailable = function (query) {
  16490. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16491. };
  16492. /**
  16493. * Gets the value of a given query
  16494. * @param query defines the query to check
  16495. * @returns the value of the query
  16496. */
  16497. Engine.prototype.getQueryResult = function (query) {
  16498. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16499. };
  16500. /**
  16501. * Initiates an occlusion query
  16502. * @param algorithmType defines the algorithm to use
  16503. * @param query defines the query to use
  16504. * @returns the current engine
  16505. * @see http://doc.babylonjs.com/features/occlusionquery
  16506. */
  16507. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16508. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16509. this._gl.beginQuery(glAlgorithm, query);
  16510. return this;
  16511. };
  16512. /**
  16513. * Ends an occlusion query
  16514. * @see http://doc.babylonjs.com/features/occlusionquery
  16515. * @param algorithmType defines the algorithm to use
  16516. * @returns the current engine
  16517. */
  16518. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16519. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16520. this._gl.endQuery(glAlgorithm);
  16521. return this;
  16522. };
  16523. /* Time queries */
  16524. Engine.prototype._createTimeQuery = function () {
  16525. var timerQuery = this._caps.timerQuery;
  16526. if (timerQuery.createQueryEXT) {
  16527. return timerQuery.createQueryEXT();
  16528. }
  16529. return this.createQuery();
  16530. };
  16531. Engine.prototype._deleteTimeQuery = function (query) {
  16532. var timerQuery = this._caps.timerQuery;
  16533. if (timerQuery.deleteQueryEXT) {
  16534. timerQuery.deleteQueryEXT(query);
  16535. return;
  16536. }
  16537. this.deleteQuery(query);
  16538. };
  16539. Engine.prototype._getTimeQueryResult = function (query) {
  16540. var timerQuery = this._caps.timerQuery;
  16541. if (timerQuery.getQueryObjectEXT) {
  16542. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16543. }
  16544. return this.getQueryResult(query);
  16545. };
  16546. Engine.prototype._getTimeQueryAvailability = function (query) {
  16547. var timerQuery = this._caps.timerQuery;
  16548. if (timerQuery.getQueryObjectEXT) {
  16549. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16550. }
  16551. return this.isQueryResultAvailable(query);
  16552. };
  16553. /**
  16554. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16555. * Please note that only one query can be issued at a time
  16556. * @returns a time token used to track the time span
  16557. */
  16558. Engine.prototype.startTimeQuery = function () {
  16559. var timerQuery = this._caps.timerQuery;
  16560. if (!timerQuery) {
  16561. return null;
  16562. }
  16563. var token = new BABYLON._TimeToken();
  16564. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16565. if (this._caps.canUseTimestampForTimerQuery) {
  16566. token._startTimeQuery = this._createTimeQuery();
  16567. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16568. }
  16569. else {
  16570. if (this._currentNonTimestampToken) {
  16571. return this._currentNonTimestampToken;
  16572. }
  16573. token._timeElapsedQuery = this._createTimeQuery();
  16574. if (timerQuery.beginQueryEXT) {
  16575. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16576. }
  16577. else {
  16578. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16579. }
  16580. this._currentNonTimestampToken = token;
  16581. }
  16582. return token;
  16583. };
  16584. /**
  16585. * Ends a time query
  16586. * @param token defines the token used to measure the time span
  16587. * @returns the time spent (in ns)
  16588. */
  16589. Engine.prototype.endTimeQuery = function (token) {
  16590. var timerQuery = this._caps.timerQuery;
  16591. if (!timerQuery || !token) {
  16592. return -1;
  16593. }
  16594. if (this._caps.canUseTimestampForTimerQuery) {
  16595. if (!token._startTimeQuery) {
  16596. return -1;
  16597. }
  16598. if (!token._endTimeQuery) {
  16599. token._endTimeQuery = this._createTimeQuery();
  16600. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16601. }
  16602. }
  16603. else if (!token._timeElapsedQueryEnded) {
  16604. if (!token._timeElapsedQuery) {
  16605. return -1;
  16606. }
  16607. if (timerQuery.endQueryEXT) {
  16608. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16609. }
  16610. else {
  16611. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16612. }
  16613. token._timeElapsedQueryEnded = true;
  16614. }
  16615. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16616. var available = false;
  16617. if (token._endTimeQuery) {
  16618. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16619. }
  16620. else if (token._timeElapsedQuery) {
  16621. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16622. }
  16623. if (available && !disjoint) {
  16624. var result = 0;
  16625. if (this._caps.canUseTimestampForTimerQuery) {
  16626. if (!token._startTimeQuery || !token._endTimeQuery) {
  16627. return -1;
  16628. }
  16629. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16630. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16631. result = timeEnd - timeStart;
  16632. this._deleteTimeQuery(token._startTimeQuery);
  16633. this._deleteTimeQuery(token._endTimeQuery);
  16634. token._startTimeQuery = null;
  16635. token._endTimeQuery = null;
  16636. }
  16637. else {
  16638. if (!token._timeElapsedQuery) {
  16639. return -1;
  16640. }
  16641. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16642. this._deleteTimeQuery(token._timeElapsedQuery);
  16643. token._timeElapsedQuery = null;
  16644. token._timeElapsedQueryEnded = false;
  16645. this._currentNonTimestampToken = null;
  16646. }
  16647. return result;
  16648. }
  16649. return -1;
  16650. };
  16651. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16652. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16653. };
  16654. // Transform feedback
  16655. /**
  16656. * Creates a webGL transform feedback object
  16657. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16658. * @returns the webGL transform feedback object
  16659. */
  16660. Engine.prototype.createTransformFeedback = function () {
  16661. return this._gl.createTransformFeedback();
  16662. };
  16663. /**
  16664. * Delete a webGL transform feedback object
  16665. * @param value defines the webGL transform feedback object to delete
  16666. */
  16667. Engine.prototype.deleteTransformFeedback = function (value) {
  16668. this._gl.deleteTransformFeedback(value);
  16669. };
  16670. /**
  16671. * Bind a webGL transform feedback object to the webgl context
  16672. * @param value defines the webGL transform feedback object to bind
  16673. */
  16674. Engine.prototype.bindTransformFeedback = function (value) {
  16675. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16676. };
  16677. /**
  16678. * Begins a transform feedback operation
  16679. * @param usePoints defines if points or triangles must be used
  16680. */
  16681. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16682. if (usePoints === void 0) { usePoints = true; }
  16683. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16684. };
  16685. /**
  16686. * Ends a transform feedback operation
  16687. */
  16688. Engine.prototype.endTransformFeedback = function () {
  16689. this._gl.endTransformFeedback();
  16690. };
  16691. /**
  16692. * Specify the varyings to use with transform feedback
  16693. * @param program defines the associated webGL program
  16694. * @param value defines the list of strings representing the varying names
  16695. */
  16696. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16697. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16698. };
  16699. /**
  16700. * Bind a webGL buffer for a transform feedback operation
  16701. * @param value defines the webGL buffer to bind
  16702. */
  16703. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16704. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16705. };
  16706. /** @ignore */
  16707. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16708. var _this = this;
  16709. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16710. this._activeRequests.push(request);
  16711. request.onCompleteObservable.add(function (request) {
  16712. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16713. });
  16714. return request;
  16715. };
  16716. /** @ignore */
  16717. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16718. var _this = this;
  16719. return new Promise(function (resolve, reject) {
  16720. _this._loadFile(url, function (data) {
  16721. resolve(data);
  16722. }, undefined, database, useArrayBuffer, function (request, exception) {
  16723. reject(exception);
  16724. });
  16725. });
  16726. };
  16727. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16728. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16729. var onload = function (data) {
  16730. loadedFiles[index] = data;
  16731. loadedFiles._internalCount++;
  16732. if (loadedFiles._internalCount === 6) {
  16733. onfinish(loadedFiles);
  16734. }
  16735. };
  16736. var onerror = function (request, exception) {
  16737. if (onErrorCallBack && request) {
  16738. onErrorCallBack(request.status + " " + request.statusText, exception);
  16739. }
  16740. };
  16741. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16742. };
  16743. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16744. if (onError === void 0) { onError = null; }
  16745. var loadedFiles = [];
  16746. loadedFiles._internalCount = 0;
  16747. for (var index = 0; index < 6; index++) {
  16748. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16749. }
  16750. };
  16751. // Statics
  16752. /**
  16753. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16754. * @returns true if the engine can be created
  16755. * @ignoreNaming
  16756. */
  16757. Engine.isSupported = function () {
  16758. try {
  16759. var tempcanvas = document.createElement("canvas");
  16760. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16761. return gl != null && !!window.WebGLRenderingContext;
  16762. }
  16763. catch (e) {
  16764. return false;
  16765. }
  16766. };
  16767. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16768. Engine.ExceptionList = [
  16769. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16770. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16771. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16772. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16773. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16774. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  16775. ];
  16776. /** Gets the list of created engines */
  16777. Engine.Instances = new Array();
  16778. // Const statics
  16779. Engine._ALPHA_DISABLE = 0;
  16780. Engine._ALPHA_ADD = 1;
  16781. Engine._ALPHA_COMBINE = 2;
  16782. Engine._ALPHA_SUBTRACT = 3;
  16783. Engine._ALPHA_MULTIPLY = 4;
  16784. Engine._ALPHA_MAXIMIZED = 5;
  16785. Engine._ALPHA_ONEONE = 6;
  16786. Engine._ALPHA_PREMULTIPLIED = 7;
  16787. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  16788. Engine._ALPHA_INTERPOLATE = 9;
  16789. Engine._ALPHA_SCREENMODE = 10;
  16790. Engine._DELAYLOADSTATE_NONE = 0;
  16791. Engine._DELAYLOADSTATE_LOADED = 1;
  16792. Engine._DELAYLOADSTATE_LOADING = 2;
  16793. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  16794. Engine._TEXTUREFORMAT_ALPHA = 0;
  16795. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  16796. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  16797. Engine._TEXTUREFORMAT_RGB = 4;
  16798. Engine._TEXTUREFORMAT_RGBA = 5;
  16799. Engine._TEXTUREFORMAT_R32F = 6;
  16800. Engine._TEXTUREFORMAT_RG32F = 7;
  16801. Engine._TEXTUREFORMAT_RGB32F = 8;
  16802. Engine._TEXTUREFORMAT_RGBA32F = 9;
  16803. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  16804. Engine._TEXTURETYPE_FLOAT = 1;
  16805. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  16806. // Depht or Stencil test Constants.
  16807. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  16808. 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.
  16809. 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.
  16810. 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.
  16811. 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.
  16812. 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.
  16813. 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.
  16814. 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.
  16815. // Stencil Actions Constants.
  16816. Engine._KEEP = 0x1E00;
  16817. Engine._REPLACE = 0x1E01;
  16818. Engine._INCR = 0x1E02;
  16819. Engine._DECR = 0x1E03;
  16820. Engine._INVERT = 0x150A;
  16821. Engine._INCR_WRAP = 0x8507;
  16822. Engine._DECR_WRAP = 0x8508;
  16823. // Texture rescaling mode
  16824. Engine._SCALEMODE_FLOOR = 1;
  16825. Engine._SCALEMODE_NEAREST = 2;
  16826. Engine._SCALEMODE_CEILING = 3;
  16827. // Updatable statics so stick with vars here
  16828. /**
  16829. * Gets or sets the epsilon value used by collision engine
  16830. */
  16831. Engine.CollisionsEpsilon = 0.001;
  16832. /**
  16833. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  16834. */
  16835. Engine.CodeRepository = "src/";
  16836. /**
  16837. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  16838. */
  16839. Engine.ShadersRepository = "src/Shaders/";
  16840. return Engine;
  16841. }());
  16842. BABYLON.Engine = Engine;
  16843. })(BABYLON || (BABYLON = {}));
  16844. //# sourceMappingURL=babylon.engine.js.map
  16845. "use strict";
  16846. var BABYLON;
  16847. (function (BABYLON) {
  16848. /**
  16849. * Node is the basic class for all scene objects (Mesh, Light Camera).
  16850. */
  16851. var Node = /** @class */ (function () {
  16852. /**
  16853. * Creates a new Node
  16854. * @param {string} name - the name and id to be given to this node
  16855. * @param {BABYLON.Scene} the scene this node will be added to
  16856. */
  16857. function Node(name, scene) {
  16858. if (scene === void 0) { scene = null; }
  16859. /**
  16860. * Gets or sets a string used to store user defined state for the node
  16861. */
  16862. this.state = "";
  16863. /**
  16864. * Gets or sets an object used to store user defined information for the node
  16865. */
  16866. this.metadata = null;
  16867. /**
  16868. * Gets or sets a boolean used to define if the node must be serialized
  16869. */
  16870. this.doNotSerialize = false;
  16871. /** @ignore */
  16872. this._isDisposed = false;
  16873. /**
  16874. * Gets a list of Animations associated with the node
  16875. */
  16876. this.animations = new Array();
  16877. this._ranges = {};
  16878. this._isEnabled = true;
  16879. this._isReady = true;
  16880. /** @ignore */
  16881. this._currentRenderId = -1;
  16882. this._parentRenderId = -1;
  16883. this._childRenderId = -1;
  16884. this._animationPropertiesOverride = null;
  16885. /**
  16886. * An event triggered when the mesh is disposed
  16887. */
  16888. this.onDisposeObservable = new BABYLON.Observable();
  16889. // Behaviors
  16890. this._behaviors = new Array();
  16891. this.name = name;
  16892. this.id = name;
  16893. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  16894. this.uniqueId = this._scene.getUniqueId();
  16895. this._initCache();
  16896. }
  16897. /**
  16898. * Gets a boolean indicating if the node has been disposed
  16899. * @returns true if the node was disposed
  16900. */
  16901. Node.prototype.isDisposed = function () {
  16902. return this._isDisposed;
  16903. };
  16904. Object.defineProperty(Node.prototype, "parent", {
  16905. get: function () {
  16906. return this._parentNode;
  16907. },
  16908. /**
  16909. * Gets or sets the parent of the node
  16910. */
  16911. set: function (parent) {
  16912. if (this._parentNode === parent) {
  16913. return;
  16914. }
  16915. // Remove self from list of children of parent
  16916. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  16917. var index = this._parentNode._children.indexOf(this);
  16918. if (index !== -1) {
  16919. this._parentNode._children.splice(index, 1);
  16920. }
  16921. }
  16922. // Store new parent
  16923. this._parentNode = parent;
  16924. // Add as child to new parent
  16925. if (this._parentNode) {
  16926. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  16927. this._parentNode._children = new Array();
  16928. }
  16929. this._parentNode._children.push(this);
  16930. }
  16931. },
  16932. enumerable: true,
  16933. configurable: true
  16934. });
  16935. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  16936. /**
  16937. * Gets or sets the animation properties override
  16938. */
  16939. get: function () {
  16940. return this._animationPropertiesOverride;
  16941. },
  16942. set: function (value) {
  16943. this._animationPropertiesOverride = value;
  16944. },
  16945. enumerable: true,
  16946. configurable: true
  16947. });
  16948. /**
  16949. * Gets a string idenfifying the name of the class
  16950. * @returns "Node" string
  16951. */
  16952. Node.prototype.getClassName = function () {
  16953. return "Node";
  16954. };
  16955. Object.defineProperty(Node.prototype, "onDispose", {
  16956. /**
  16957. * Sets a callback that will be raised when the node will be disposed
  16958. */
  16959. set: function (callback) {
  16960. if (this._onDisposeObserver) {
  16961. this.onDisposeObservable.remove(this._onDisposeObserver);
  16962. }
  16963. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. /**
  16969. * Gets the scene of the node
  16970. * @returns a {BABYLON.Scene}
  16971. */
  16972. Node.prototype.getScene = function () {
  16973. return this._scene;
  16974. };
  16975. /**
  16976. * Gets the engine of the node
  16977. * @returns a {BABYLON.Engine}
  16978. */
  16979. Node.prototype.getEngine = function () {
  16980. return this._scene.getEngine();
  16981. };
  16982. /**
  16983. * Attach a behavior to the node
  16984. * @see http://doc.babylonjs.com/features/behaviour
  16985. * @param behavior defines the behavior to attach
  16986. * @returns the current Node
  16987. */
  16988. Node.prototype.addBehavior = function (behavior) {
  16989. var _this = this;
  16990. var index = this._behaviors.indexOf(behavior);
  16991. if (index !== -1) {
  16992. return this;
  16993. }
  16994. behavior.init();
  16995. if (this._scene.isLoading) {
  16996. // We defer the attach when the scene will be loaded
  16997. var observer = this._scene.onDataLoadedObservable.add(function () {
  16998. behavior.attach(_this);
  16999. setTimeout(function () {
  17000. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17001. _this._scene.onDataLoadedObservable.remove(observer);
  17002. }, 0);
  17003. });
  17004. }
  17005. else {
  17006. behavior.attach(this);
  17007. }
  17008. this._behaviors.push(behavior);
  17009. return this;
  17010. };
  17011. /**
  17012. * Remove an attached behavior
  17013. * @see http://doc.babylonjs.com/features/behaviour
  17014. * @param behavior defines the behavior to attach
  17015. * @returns the current Node
  17016. */
  17017. Node.prototype.removeBehavior = function (behavior) {
  17018. var index = this._behaviors.indexOf(behavior);
  17019. if (index === -1) {
  17020. return this;
  17021. }
  17022. this._behaviors[index].detach();
  17023. this._behaviors.splice(index, 1);
  17024. return this;
  17025. };
  17026. Object.defineProperty(Node.prototype, "behaviors", {
  17027. /**
  17028. * Gets the list of attached behaviors
  17029. * @see http://doc.babylonjs.com/features/behaviour
  17030. */
  17031. get: function () {
  17032. return this._behaviors;
  17033. },
  17034. enumerable: true,
  17035. configurable: true
  17036. });
  17037. /**
  17038. * Gets an attached behavior by name
  17039. * @param name defines the name of the behavior to look for
  17040. * @see http://doc.babylonjs.com/features/behaviour
  17041. * @returns null if behavior was not found else the requested behavior
  17042. */
  17043. Node.prototype.getBehaviorByName = function (name) {
  17044. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17045. var behavior = _a[_i];
  17046. if (behavior.name === name) {
  17047. return behavior;
  17048. }
  17049. }
  17050. return null;
  17051. };
  17052. /**
  17053. * Returns the world matrix of the node
  17054. * @returns a matrix containing the node's world matrix
  17055. */
  17056. Node.prototype.getWorldMatrix = function () {
  17057. return BABYLON.Matrix.Identity();
  17058. };
  17059. // override it in derived class if you add new variables to the cache
  17060. // and call the parent class method
  17061. /** @ignore */
  17062. Node.prototype._initCache = function () {
  17063. this._cache = {};
  17064. this._cache.parent = undefined;
  17065. };
  17066. /** @ignore */
  17067. Node.prototype.updateCache = function (force) {
  17068. if (!force && this.isSynchronized())
  17069. return;
  17070. this._cache.parent = this.parent;
  17071. this._updateCache();
  17072. };
  17073. // override it in derived class if you add new variables to the cache
  17074. // and call the parent class method if !ignoreParentClass
  17075. /** @ignore */
  17076. Node.prototype._updateCache = function (ignoreParentClass) {
  17077. };
  17078. // override it in derived class if you add new variables to the cache
  17079. /** @ignore */
  17080. Node.prototype._isSynchronized = function () {
  17081. return true;
  17082. };
  17083. /** @ignore */
  17084. Node.prototype._markSyncedWithParent = function () {
  17085. if (this.parent) {
  17086. this._parentRenderId = this.parent._childRenderId;
  17087. }
  17088. };
  17089. /** @ignore */
  17090. Node.prototype.isSynchronizedWithParent = function () {
  17091. if (!this.parent) {
  17092. return true;
  17093. }
  17094. if (this._parentRenderId !== this.parent._childRenderId) {
  17095. return false;
  17096. }
  17097. return this.parent.isSynchronized();
  17098. };
  17099. /** @ignore */
  17100. Node.prototype.isSynchronized = function (updateCache) {
  17101. var check = this.hasNewParent();
  17102. check = check || !this.isSynchronizedWithParent();
  17103. check = check || !this._isSynchronized();
  17104. if (updateCache)
  17105. this.updateCache(true);
  17106. return !check;
  17107. };
  17108. /** @ignore */
  17109. Node.prototype.hasNewParent = function (update) {
  17110. if (this._cache.parent === this.parent)
  17111. return false;
  17112. if (update)
  17113. this._cache.parent = this.parent;
  17114. return true;
  17115. };
  17116. /**
  17117. * Is this node ready to be used/rendered
  17118. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17119. * @return true if the node is ready
  17120. */
  17121. Node.prototype.isReady = function (completeCheck) {
  17122. if (completeCheck === void 0) { completeCheck = false; }
  17123. return this._isReady;
  17124. };
  17125. /**
  17126. * Is this node enabled?
  17127. * 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
  17128. * @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
  17129. * @return whether this node (and its parent) is enabled
  17130. */
  17131. Node.prototype.isEnabled = function (checkAncestors) {
  17132. if (checkAncestors === void 0) { checkAncestors = true; }
  17133. if (checkAncestors === false) {
  17134. return this._isEnabled;
  17135. }
  17136. if (this._isEnabled === false) {
  17137. return false;
  17138. }
  17139. if (this.parent !== undefined && this.parent !== null) {
  17140. return this.parent.isEnabled(checkAncestors);
  17141. }
  17142. return true;
  17143. };
  17144. /**
  17145. * Set the enabled state of this node
  17146. * @param value defines the new enabled state
  17147. */
  17148. Node.prototype.setEnabled = function (value) {
  17149. this._isEnabled = value;
  17150. };
  17151. /**
  17152. * Is this node a descendant of the given node?
  17153. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17154. * @param ancestor defines the parent node to inspect
  17155. * @returns a boolean indicating if this node is a descendant of the given node
  17156. */
  17157. Node.prototype.isDescendantOf = function (ancestor) {
  17158. if (this.parent) {
  17159. if (this.parent === ancestor) {
  17160. return true;
  17161. }
  17162. return this.parent.isDescendantOf(ancestor);
  17163. }
  17164. return false;
  17165. };
  17166. /** @ignore */
  17167. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17168. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17169. if (!this._children) {
  17170. return;
  17171. }
  17172. for (var index = 0; index < this._children.length; index++) {
  17173. var item = this._children[index];
  17174. if (!predicate || predicate(item)) {
  17175. results.push(item);
  17176. }
  17177. if (!directDescendantsOnly) {
  17178. item._getDescendants(results, false, predicate);
  17179. }
  17180. }
  17181. };
  17182. /**
  17183. * Will return all nodes that have this node as ascendant
  17184. * @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
  17185. * @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
  17186. * @return all children nodes of all types
  17187. */
  17188. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17189. var results = new Array();
  17190. this._getDescendants(results, directDescendantsOnly, predicate);
  17191. return results;
  17192. };
  17193. /**
  17194. * Get all child-meshes of this node
  17195. * @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
  17196. * @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
  17197. * @returns an array of {BABYLON.AbstractMesh}
  17198. */
  17199. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17200. var results = [];
  17201. this._getDescendants(results, directDescendantsOnly, function (node) {
  17202. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17203. });
  17204. return results;
  17205. };
  17206. /**
  17207. * Get all child-transformNodes of this node
  17208. * @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
  17209. * @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
  17210. * @returns an array of {BABYLON.TransformNode}
  17211. */
  17212. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17213. var results = [];
  17214. this._getDescendants(results, directDescendantsOnly, function (node) {
  17215. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17216. });
  17217. return results;
  17218. };
  17219. /**
  17220. * Get all direct children of this node
  17221. * @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
  17222. * @returns an array of {BABYLON.Node}
  17223. */
  17224. Node.prototype.getChildren = function (predicate) {
  17225. return this.getDescendants(true, predicate);
  17226. };
  17227. /** @ignore */
  17228. Node.prototype._setReady = function (state) {
  17229. if (state === this._isReady) {
  17230. return;
  17231. }
  17232. if (!state) {
  17233. this._isReady = false;
  17234. return;
  17235. }
  17236. if (this.onReady) {
  17237. this.onReady(this);
  17238. }
  17239. this._isReady = true;
  17240. };
  17241. /**
  17242. * Get an animation by name
  17243. * @param name defines the name of the animation to look for
  17244. * @returns null if not found else the requested animation
  17245. */
  17246. Node.prototype.getAnimationByName = function (name) {
  17247. for (var i = 0; i < this.animations.length; i++) {
  17248. var animation = this.animations[i];
  17249. if (animation.name === name) {
  17250. return animation;
  17251. }
  17252. }
  17253. return null;
  17254. };
  17255. /**
  17256. * Creates an animation range for this node
  17257. * @param name defines the name of the range
  17258. * @param from defines the starting key
  17259. * @param to defines the end key
  17260. */
  17261. Node.prototype.createAnimationRange = function (name, from, to) {
  17262. // check name not already in use
  17263. if (!this._ranges[name]) {
  17264. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17265. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17266. if (this.animations[i]) {
  17267. this.animations[i].createRange(name, from, to);
  17268. }
  17269. }
  17270. }
  17271. };
  17272. /**
  17273. * Delete a specific animation range
  17274. * @param name defines the name of the range to delete
  17275. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17276. */
  17277. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17278. if (deleteFrames === void 0) { deleteFrames = true; }
  17279. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17280. if (this.animations[i]) {
  17281. this.animations[i].deleteRange(name, deleteFrames);
  17282. }
  17283. }
  17284. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17285. };
  17286. /**
  17287. * Get an animation range by name
  17288. * @param name defines the name of the animation range to look for
  17289. * @returns null if not found else the requested animation range
  17290. */
  17291. Node.prototype.getAnimationRange = function (name) {
  17292. return this._ranges[name];
  17293. };
  17294. /**
  17295. * Will start the animation sequence
  17296. * @param name defines the range frames for animation sequence
  17297. * @param loop defines if the animation should loop (false by default)
  17298. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17299. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17300. * @returns the object created for this animation. If range does not exist, it will return null
  17301. */
  17302. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17303. var range = this.getAnimationRange(name);
  17304. if (!range) {
  17305. return null;
  17306. }
  17307. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17308. };
  17309. /**
  17310. * Serialize animation ranges into a JSON compatible object
  17311. * @returns serialization object
  17312. */
  17313. Node.prototype.serializeAnimationRanges = function () {
  17314. var serializationRanges = [];
  17315. for (var name in this._ranges) {
  17316. var localRange = this._ranges[name];
  17317. if (!localRange) {
  17318. continue;
  17319. }
  17320. var range = {};
  17321. range.name = name;
  17322. range.from = localRange.from;
  17323. range.to = localRange.to;
  17324. serializationRanges.push(range);
  17325. }
  17326. return serializationRanges;
  17327. };
  17328. /**
  17329. * Computes the world matrix of the node
  17330. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17331. * @returns the world matrix
  17332. */
  17333. Node.prototype.computeWorldMatrix = function (force) {
  17334. return BABYLON.Matrix.Identity();
  17335. };
  17336. /**
  17337. * Releases resources associated with this node.
  17338. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17339. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17340. */
  17341. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17342. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17343. if (!doNotRecurse) {
  17344. var nodes = this.getDescendants(true);
  17345. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17346. var node = nodes_1[_i];
  17347. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17348. }
  17349. }
  17350. else {
  17351. var transformNodes = this.getChildTransformNodes(true);
  17352. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17353. var transformNode = transformNodes_1[_a];
  17354. transformNode.parent = null;
  17355. transformNode.computeWorldMatrix(true);
  17356. }
  17357. }
  17358. this.parent = null;
  17359. // Callback
  17360. this.onDisposeObservable.notifyObservers(this);
  17361. this.onDisposeObservable.clear();
  17362. // Behaviors
  17363. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17364. var behavior = _c[_b];
  17365. behavior.detach();
  17366. }
  17367. this._behaviors = [];
  17368. this._isDisposed = true;
  17369. };
  17370. /**
  17371. * Parse animation range data from a serialization object and store them into a given node
  17372. * @param node defines where to store the animation ranges
  17373. * @param parsedNode defines the serialization object to read data from
  17374. * @param scene defines the hosting scene
  17375. */
  17376. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17377. if (parsedNode.ranges) {
  17378. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17379. var data = parsedNode.ranges[index];
  17380. node.createAnimationRange(data.name, data.from, data.to);
  17381. }
  17382. }
  17383. };
  17384. __decorate([
  17385. BABYLON.serialize()
  17386. ], Node.prototype, "name", void 0);
  17387. __decorate([
  17388. BABYLON.serialize()
  17389. ], Node.prototype, "id", void 0);
  17390. __decorate([
  17391. BABYLON.serialize()
  17392. ], Node.prototype, "uniqueId", void 0);
  17393. __decorate([
  17394. BABYLON.serialize()
  17395. ], Node.prototype, "state", void 0);
  17396. __decorate([
  17397. BABYLON.serialize()
  17398. ], Node.prototype, "metadata", void 0);
  17399. return Node;
  17400. }());
  17401. BABYLON.Node = Node;
  17402. })(BABYLON || (BABYLON = {}));
  17403. //# sourceMappingURL=babylon.node.js.map
  17404. "use strict";
  17405. var BABYLON;
  17406. (function (BABYLON) {
  17407. var BoundingSphere = /** @class */ (function () {
  17408. function BoundingSphere(minimum, maximum) {
  17409. this.minimum = minimum;
  17410. this.maximum = maximum;
  17411. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17412. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17413. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17414. this.radius = distance * 0.5;
  17415. this.centerWorld = BABYLON.Vector3.Zero();
  17416. this._update(BABYLON.Matrix.Identity());
  17417. }
  17418. // Methods
  17419. BoundingSphere.prototype._update = function (world) {
  17420. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17421. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17422. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17423. };
  17424. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17425. for (var i = 0; i < 6; i++) {
  17426. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17427. return false;
  17428. }
  17429. return true;
  17430. };
  17431. BoundingSphere.prototype.intersectsPoint = function (point) {
  17432. var x = this.centerWorld.x - point.x;
  17433. var y = this.centerWorld.y - point.y;
  17434. var z = this.centerWorld.z - point.z;
  17435. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17436. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17437. return false;
  17438. return true;
  17439. };
  17440. // Statics
  17441. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17442. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17443. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17444. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17445. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17446. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17447. return false;
  17448. return true;
  17449. };
  17450. return BoundingSphere;
  17451. }());
  17452. BABYLON.BoundingSphere = BoundingSphere;
  17453. })(BABYLON || (BABYLON = {}));
  17454. //# sourceMappingURL=babylon.boundingSphere.js.map
  17455. "use strict";
  17456. var BABYLON;
  17457. (function (BABYLON) {
  17458. var BoundingBox = /** @class */ (function () {
  17459. function BoundingBox(minimum, maximum) {
  17460. this.minimum = minimum;
  17461. this.maximum = maximum;
  17462. this.vectors = new Array();
  17463. this.vectorsWorld = new Array();
  17464. // Bounding vectors
  17465. this.vectors.push(this.minimum.clone());
  17466. this.vectors.push(this.maximum.clone());
  17467. this.vectors.push(this.minimum.clone());
  17468. this.vectors[2].x = this.maximum.x;
  17469. this.vectors.push(this.minimum.clone());
  17470. this.vectors[3].y = this.maximum.y;
  17471. this.vectors.push(this.minimum.clone());
  17472. this.vectors[4].z = this.maximum.z;
  17473. this.vectors.push(this.maximum.clone());
  17474. this.vectors[5].z = this.minimum.z;
  17475. this.vectors.push(this.maximum.clone());
  17476. this.vectors[6].x = this.minimum.x;
  17477. this.vectors.push(this.maximum.clone());
  17478. this.vectors[7].y = this.minimum.y;
  17479. // OBB
  17480. this.center = this.maximum.add(this.minimum).scale(0.5);
  17481. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17482. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17483. // World
  17484. for (var index = 0; index < this.vectors.length; index++) {
  17485. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17486. }
  17487. this.minimumWorld = BABYLON.Vector3.Zero();
  17488. this.maximumWorld = BABYLON.Vector3.Zero();
  17489. this.centerWorld = BABYLON.Vector3.Zero();
  17490. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17491. this._update(BABYLON.Matrix.Identity());
  17492. }
  17493. // Methods
  17494. BoundingBox.prototype.getWorldMatrix = function () {
  17495. return this._worldMatrix;
  17496. };
  17497. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17498. this._worldMatrix.copyFrom(matrix);
  17499. return this;
  17500. };
  17501. BoundingBox.prototype._update = function (world) {
  17502. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17503. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17504. for (var index = 0; index < this.vectors.length; index++) {
  17505. var v = this.vectorsWorld[index];
  17506. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17507. if (v.x < this.minimumWorld.x)
  17508. this.minimumWorld.x = v.x;
  17509. if (v.y < this.minimumWorld.y)
  17510. this.minimumWorld.y = v.y;
  17511. if (v.z < this.minimumWorld.z)
  17512. this.minimumWorld.z = v.z;
  17513. if (v.x > this.maximumWorld.x)
  17514. this.maximumWorld.x = v.x;
  17515. if (v.y > this.maximumWorld.y)
  17516. this.maximumWorld.y = v.y;
  17517. if (v.z > this.maximumWorld.z)
  17518. this.maximumWorld.z = v.z;
  17519. }
  17520. // Extend
  17521. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17522. this.extendSizeWorld.scaleInPlace(0.5);
  17523. // OBB
  17524. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17525. this.centerWorld.scaleInPlace(0.5);
  17526. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17527. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17528. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17529. this._worldMatrix = world;
  17530. };
  17531. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17532. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17533. };
  17534. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17535. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17536. };
  17537. BoundingBox.prototype.intersectsPoint = function (point) {
  17538. var delta = -BABYLON.Epsilon;
  17539. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17540. return false;
  17541. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17542. return false;
  17543. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17544. return false;
  17545. return true;
  17546. };
  17547. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17548. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17549. };
  17550. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17551. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17552. return false;
  17553. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17554. return false;
  17555. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17556. return false;
  17557. return true;
  17558. };
  17559. // Statics
  17560. BoundingBox.Intersects = function (box0, box1) {
  17561. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17562. return false;
  17563. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17564. return false;
  17565. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17566. return false;
  17567. return true;
  17568. };
  17569. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17570. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17571. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17572. return (num <= (sphereRadius * sphereRadius));
  17573. };
  17574. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17575. for (var p = 0; p < 6; p++) {
  17576. for (var i = 0; i < 8; i++) {
  17577. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17578. return false;
  17579. }
  17580. }
  17581. }
  17582. return true;
  17583. };
  17584. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17585. for (var p = 0; p < 6; p++) {
  17586. var inCount = 8;
  17587. for (var i = 0; i < 8; i++) {
  17588. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17589. --inCount;
  17590. }
  17591. else {
  17592. break;
  17593. }
  17594. }
  17595. if (inCount === 0)
  17596. return false;
  17597. }
  17598. return true;
  17599. };
  17600. return BoundingBox;
  17601. }());
  17602. BABYLON.BoundingBox = BoundingBox;
  17603. })(BABYLON || (BABYLON = {}));
  17604. //# sourceMappingURL=babylon.boundingBox.js.map
  17605. "use strict";
  17606. var BABYLON;
  17607. (function (BABYLON) {
  17608. var computeBoxExtents = function (axis, box) {
  17609. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17610. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17611. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17612. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17613. var r = r0 + r1 + r2;
  17614. return {
  17615. min: p - r,
  17616. max: p + r
  17617. };
  17618. };
  17619. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17620. var axisOverlap = function (axis, box0, box1) {
  17621. var result0 = computeBoxExtents(axis, box0);
  17622. var result1 = computeBoxExtents(axis, box1);
  17623. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17624. };
  17625. var BoundingInfo = /** @class */ (function () {
  17626. function BoundingInfo(minimum, maximum) {
  17627. this.minimum = minimum;
  17628. this.maximum = maximum;
  17629. this._isLocked = false;
  17630. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17631. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17632. }
  17633. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17634. get: function () {
  17635. return this._isLocked;
  17636. },
  17637. set: function (value) {
  17638. this._isLocked = value;
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. // Methods
  17644. BoundingInfo.prototype.update = function (world) {
  17645. if (this._isLocked) {
  17646. return;
  17647. }
  17648. this.boundingBox._update(world);
  17649. this.boundingSphere._update(world);
  17650. };
  17651. /**
  17652. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17653. * @param center New center of the bounding info
  17654. * @param extend New extend of the bounding info
  17655. */
  17656. BoundingInfo.prototype.centerOn = function (center, extend) {
  17657. this.minimum = center.subtract(extend);
  17658. this.maximum = center.add(extend);
  17659. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17660. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17661. return this;
  17662. };
  17663. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17664. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17665. return false;
  17666. return this.boundingBox.isInFrustum(frustumPlanes);
  17667. };
  17668. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17669. /**
  17670. * Gets the world distance between the min and max points of the bounding box
  17671. */
  17672. get: function () {
  17673. var boundingBox = this.boundingBox;
  17674. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17675. return size.length();
  17676. },
  17677. enumerable: true,
  17678. configurable: true
  17679. });
  17680. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17681. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17682. };
  17683. BoundingInfo.prototype._checkCollision = function (collider) {
  17684. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17685. };
  17686. BoundingInfo.prototype.intersectsPoint = function (point) {
  17687. if (!this.boundingSphere.centerWorld) {
  17688. return false;
  17689. }
  17690. if (!this.boundingSphere.intersectsPoint(point)) {
  17691. return false;
  17692. }
  17693. if (!this.boundingBox.intersectsPoint(point)) {
  17694. return false;
  17695. }
  17696. return true;
  17697. };
  17698. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17699. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17700. return false;
  17701. }
  17702. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17703. return false;
  17704. }
  17705. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17706. return false;
  17707. }
  17708. if (!precise) {
  17709. return true;
  17710. }
  17711. var box0 = this.boundingBox;
  17712. var box1 = boundingInfo.boundingBox;
  17713. if (!axisOverlap(box0.directions[0], box0, box1))
  17714. return false;
  17715. if (!axisOverlap(box0.directions[1], box0, box1))
  17716. return false;
  17717. if (!axisOverlap(box0.directions[2], box0, box1))
  17718. return false;
  17719. if (!axisOverlap(box1.directions[0], box0, box1))
  17720. return false;
  17721. if (!axisOverlap(box1.directions[1], box0, box1))
  17722. return false;
  17723. if (!axisOverlap(box1.directions[2], box0, box1))
  17724. return false;
  17725. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  17726. return false;
  17727. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  17728. return false;
  17729. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  17730. return false;
  17731. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  17732. return false;
  17733. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  17734. return false;
  17735. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  17736. return false;
  17737. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  17738. return false;
  17739. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  17740. return false;
  17741. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  17742. return false;
  17743. return true;
  17744. };
  17745. return BoundingInfo;
  17746. }());
  17747. BABYLON.BoundingInfo = BoundingInfo;
  17748. })(BABYLON || (BABYLON = {}));
  17749. //# sourceMappingURL=babylon.boundingInfo.js.map
  17750. "use strict";
  17751. var BABYLON;
  17752. (function (BABYLON) {
  17753. var TransformNode = /** @class */ (function (_super) {
  17754. __extends(TransformNode, _super);
  17755. function TransformNode(name, scene, isPure) {
  17756. if (scene === void 0) { scene = null; }
  17757. if (isPure === void 0) { isPure = true; }
  17758. var _this = _super.call(this, name, scene) || this;
  17759. _this._forward = new BABYLON.Vector3(0, 0, 1);
  17760. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  17761. _this._up = new BABYLON.Vector3(0, 1, 0);
  17762. _this._right = new BABYLON.Vector3(1, 0, 0);
  17763. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  17764. // Properties
  17765. _this._rotation = BABYLON.Vector3.Zero();
  17766. _this._scaling = BABYLON.Vector3.One();
  17767. _this._isDirty = false;
  17768. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  17769. _this.scalingDeterminant = 1;
  17770. _this.infiniteDistance = false;
  17771. _this.position = BABYLON.Vector3.Zero();
  17772. _this._localWorld = BABYLON.Matrix.Zero();
  17773. _this._worldMatrix = BABYLON.Matrix.Zero();
  17774. _this._worldMatrixDeterminant = 0;
  17775. _this._absolutePosition = BABYLON.Vector3.Zero();
  17776. _this._pivotMatrix = BABYLON.Matrix.Identity();
  17777. _this._postMultiplyPivotMatrix = false;
  17778. _this._isWorldMatrixFrozen = false;
  17779. /**
  17780. * An event triggered after the world matrix is updated
  17781. */
  17782. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  17783. _this._nonUniformScaling = false;
  17784. if (isPure) {
  17785. _this.getScene().addTransformNode(_this);
  17786. }
  17787. return _this;
  17788. }
  17789. /**
  17790. * Gets a string idenfifying the name of the class
  17791. * @returns "TransformNode" string
  17792. */
  17793. TransformNode.prototype.getClassName = function () {
  17794. return "TransformNode";
  17795. };
  17796. Object.defineProperty(TransformNode.prototype, "rotation", {
  17797. /**
  17798. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  17799. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  17800. * Default : (0.0, 0.0, 0.0)
  17801. */
  17802. get: function () {
  17803. return this._rotation;
  17804. },
  17805. set: function (newRotation) {
  17806. this._rotation = newRotation;
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(TransformNode.prototype, "scaling", {
  17812. /**
  17813. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17814. * Default : (1.0, 1.0, 1.0)
  17815. */
  17816. get: function () {
  17817. return this._scaling;
  17818. },
  17819. /**
  17820. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17821. * Default : (1.0, 1.0, 1.0)
  17822. */
  17823. set: function (newScaling) {
  17824. this._scaling = newScaling;
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  17830. /**
  17831. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  17832. * It's null by default.
  17833. * 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)
  17834. */
  17835. get: function () {
  17836. return this._rotationQuaternion;
  17837. },
  17838. set: function (quaternion) {
  17839. this._rotationQuaternion = quaternion;
  17840. //reset the rotation vector.
  17841. if (quaternion && this.rotation.length()) {
  17842. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  17843. }
  17844. },
  17845. enumerable: true,
  17846. configurable: true
  17847. });
  17848. Object.defineProperty(TransformNode.prototype, "forward", {
  17849. /**
  17850. * The forward direction of that transform in world space.
  17851. */
  17852. get: function () {
  17853. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  17854. },
  17855. enumerable: true,
  17856. configurable: true
  17857. });
  17858. Object.defineProperty(TransformNode.prototype, "up", {
  17859. /**
  17860. * The up direction of that transform in world space.
  17861. */
  17862. get: function () {
  17863. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  17864. },
  17865. enumerable: true,
  17866. configurable: true
  17867. });
  17868. Object.defineProperty(TransformNode.prototype, "right", {
  17869. /**
  17870. * The right direction of that transform in world space.
  17871. */
  17872. get: function () {
  17873. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. /**
  17879. * Returns the latest update of the World matrix
  17880. * Returns a Matrix.
  17881. */
  17882. TransformNode.prototype.getWorldMatrix = function () {
  17883. if (this._currentRenderId !== this.getScene().getRenderId()) {
  17884. this.computeWorldMatrix();
  17885. }
  17886. return this._worldMatrix;
  17887. };
  17888. /**
  17889. * Returns the latest update of the World matrix determinant.
  17890. */
  17891. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  17892. return this._worldMatrixDeterminant;
  17893. };
  17894. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  17895. /**
  17896. * Returns directly the latest state of the mesh World matrix.
  17897. * A Matrix is returned.
  17898. */
  17899. get: function () {
  17900. return this._worldMatrix;
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. /**
  17906. * Copies the paramater passed Matrix into the mesh Pose matrix.
  17907. * Returns the TransformNode.
  17908. */
  17909. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  17910. this._poseMatrix.copyFrom(matrix);
  17911. return this;
  17912. };
  17913. /**
  17914. * Returns the mesh Pose matrix.
  17915. * Returned object : Matrix
  17916. */
  17917. TransformNode.prototype.getPoseMatrix = function () {
  17918. return this._poseMatrix;
  17919. };
  17920. TransformNode.prototype._isSynchronized = function () {
  17921. if (this._isDirty) {
  17922. return false;
  17923. }
  17924. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  17925. return false;
  17926. if (this._cache.pivotMatrixUpdated) {
  17927. return false;
  17928. }
  17929. if (this.infiniteDistance) {
  17930. return false;
  17931. }
  17932. if (!this._cache.position.equals(this.position))
  17933. return false;
  17934. if (this.rotationQuaternion) {
  17935. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  17936. return false;
  17937. }
  17938. if (!this._cache.rotation.equals(this.rotation))
  17939. return false;
  17940. if (!this._cache.scaling.equals(this.scaling))
  17941. return false;
  17942. return true;
  17943. };
  17944. TransformNode.prototype._initCache = function () {
  17945. _super.prototype._initCache.call(this);
  17946. this._cache.localMatrixUpdated = false;
  17947. this._cache.position = BABYLON.Vector3.Zero();
  17948. this._cache.scaling = BABYLON.Vector3.Zero();
  17949. this._cache.rotation = BABYLON.Vector3.Zero();
  17950. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  17951. this._cache.billboardMode = -1;
  17952. };
  17953. TransformNode.prototype.markAsDirty = function (property) {
  17954. if (property === "rotation") {
  17955. this.rotationQuaternion = null;
  17956. }
  17957. this._currentRenderId = Number.MAX_VALUE;
  17958. this._isDirty = true;
  17959. return this;
  17960. };
  17961. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  17962. /**
  17963. * Returns the current mesh absolute position.
  17964. * Retuns a Vector3.
  17965. */
  17966. get: function () {
  17967. return this._absolutePosition;
  17968. },
  17969. enumerable: true,
  17970. configurable: true
  17971. });
  17972. /**
  17973. * Sets a new matrix to apply before all other transformation
  17974. * @param matrix defines the transform matrix
  17975. * @returns the current TransformNode
  17976. */
  17977. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  17978. return this.setPivotMatrix(matrix, false);
  17979. };
  17980. /**
  17981. * Sets a new pivot matrix to the current node
  17982. * @param matrix defines the new pivot matrix to use
  17983. * @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
  17984. * @returns the current TransformNode
  17985. */
  17986. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  17987. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  17988. this._pivotMatrix = matrix.clone();
  17989. this._cache.pivotMatrixUpdated = true;
  17990. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  17991. if (this._postMultiplyPivotMatrix) {
  17992. if (!this._pivotMatrixInverse) {
  17993. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  17994. }
  17995. else {
  17996. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  17997. }
  17998. }
  17999. return this;
  18000. };
  18001. /**
  18002. * Returns the mesh pivot matrix.
  18003. * Default : Identity.
  18004. * A Matrix is returned.
  18005. */
  18006. TransformNode.prototype.getPivotMatrix = function () {
  18007. return this._pivotMatrix;
  18008. };
  18009. /**
  18010. * Prevents the World matrix to be computed any longer.
  18011. * Returns the TransformNode.
  18012. */
  18013. TransformNode.prototype.freezeWorldMatrix = function () {
  18014. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18015. this.computeWorldMatrix(true);
  18016. this._isWorldMatrixFrozen = true;
  18017. return this;
  18018. };
  18019. /**
  18020. * Allows back the World matrix computation.
  18021. * Returns the TransformNode.
  18022. */
  18023. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18024. this._isWorldMatrixFrozen = false;
  18025. this.computeWorldMatrix(true);
  18026. return this;
  18027. };
  18028. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18029. /**
  18030. * True if the World matrix has been frozen.
  18031. * Returns a boolean.
  18032. */
  18033. get: function () {
  18034. return this._isWorldMatrixFrozen;
  18035. },
  18036. enumerable: true,
  18037. configurable: true
  18038. });
  18039. /**
  18040. * Retuns the mesh absolute position in the World.
  18041. * Returns a Vector3.
  18042. */
  18043. TransformNode.prototype.getAbsolutePosition = function () {
  18044. this.computeWorldMatrix();
  18045. return this._absolutePosition;
  18046. };
  18047. /**
  18048. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18049. * Returns the TransformNode.
  18050. */
  18051. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18052. if (!absolutePosition) {
  18053. return this;
  18054. }
  18055. var absolutePositionX;
  18056. var absolutePositionY;
  18057. var absolutePositionZ;
  18058. if (absolutePosition.x === undefined) {
  18059. if (arguments.length < 3) {
  18060. return this;
  18061. }
  18062. absolutePositionX = arguments[0];
  18063. absolutePositionY = arguments[1];
  18064. absolutePositionZ = arguments[2];
  18065. }
  18066. else {
  18067. absolutePositionX = absolutePosition.x;
  18068. absolutePositionY = absolutePosition.y;
  18069. absolutePositionZ = absolutePosition.z;
  18070. }
  18071. if (this.parent) {
  18072. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18073. invertParentWorldMatrix.invert();
  18074. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18075. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18076. }
  18077. else {
  18078. this.position.x = absolutePositionX;
  18079. this.position.y = absolutePositionY;
  18080. this.position.z = absolutePositionZ;
  18081. }
  18082. return this;
  18083. };
  18084. /**
  18085. * Sets the mesh position in its local space.
  18086. * Returns the TransformNode.
  18087. */
  18088. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18089. this.computeWorldMatrix();
  18090. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18091. return this;
  18092. };
  18093. /**
  18094. * Returns the mesh position in the local space from the current World matrix values.
  18095. * Returns a new Vector3.
  18096. */
  18097. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18098. this.computeWorldMatrix();
  18099. var invLocalWorldMatrix = this._localWorld.clone();
  18100. invLocalWorldMatrix.invert();
  18101. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18102. };
  18103. /**
  18104. * Translates the mesh along the passed Vector3 in its local space.
  18105. * Returns the TransformNode.
  18106. */
  18107. TransformNode.prototype.locallyTranslate = function (vector3) {
  18108. this.computeWorldMatrix(true);
  18109. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18110. return this;
  18111. };
  18112. /**
  18113. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18114. * @param targetPoint the position (must be in same space as current mesh) to look at
  18115. * @param yawCor optional yaw (y-axis) correction in radians
  18116. * @param pitchCor optional pitch (x-axis) correction in radians
  18117. * @param rollCor optional roll (z-axis) correction in radians
  18118. * @param space the choosen space of the target
  18119. * @returns the TransformNode.
  18120. */
  18121. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18122. if (yawCor === void 0) { yawCor = 0; }
  18123. if (pitchCor === void 0) { pitchCor = 0; }
  18124. if (rollCor === void 0) { rollCor = 0; }
  18125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18126. var dv = TransformNode._lookAtVectorCache;
  18127. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18128. targetPoint.subtractToRef(pos, dv);
  18129. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18130. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18131. var pitch = Math.atan2(dv.y, len);
  18132. if (this.rotationQuaternion) {
  18133. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18134. }
  18135. else {
  18136. this.rotation.x = pitch + pitchCor;
  18137. this.rotation.y = yaw + yawCor;
  18138. this.rotation.z = rollCor;
  18139. }
  18140. return this;
  18141. };
  18142. /**
  18143. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18144. * This Vector3 is expressed in the World space.
  18145. */
  18146. TransformNode.prototype.getDirection = function (localAxis) {
  18147. var result = BABYLON.Vector3.Zero();
  18148. this.getDirectionToRef(localAxis, result);
  18149. return result;
  18150. };
  18151. /**
  18152. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18153. * localAxis is expressed in the mesh local space.
  18154. * result is computed in the Wordl space from the mesh World matrix.
  18155. * Returns the TransformNode.
  18156. */
  18157. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18158. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18159. return this;
  18160. };
  18161. /**
  18162. * Sets a new pivot point to the current node
  18163. * @param point defines the new pivot point to use
  18164. * @param space defines if the point is in world or local space (local by default)
  18165. * @returns the current TransformNode
  18166. */
  18167. TransformNode.prototype.setPivotPoint = function (point, space) {
  18168. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18169. if (this.getScene().getRenderId() == 0) {
  18170. this.computeWorldMatrix(true);
  18171. }
  18172. var wm = this.getWorldMatrix();
  18173. if (space == BABYLON.Space.WORLD) {
  18174. var tmat = BABYLON.Tmp.Matrix[0];
  18175. wm.invertToRef(tmat);
  18176. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18177. }
  18178. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18179. };
  18180. /**
  18181. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18182. */
  18183. TransformNode.prototype.getPivotPoint = function () {
  18184. var point = BABYLON.Vector3.Zero();
  18185. this.getPivotPointToRef(point);
  18186. return point;
  18187. };
  18188. /**
  18189. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18190. * Returns the TransformNode.
  18191. */
  18192. TransformNode.prototype.getPivotPointToRef = function (result) {
  18193. result.x = -this._pivotMatrix.m[12];
  18194. result.y = -this._pivotMatrix.m[13];
  18195. result.z = -this._pivotMatrix.m[14];
  18196. return this;
  18197. };
  18198. /**
  18199. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18200. */
  18201. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18202. var point = BABYLON.Vector3.Zero();
  18203. this.getAbsolutePivotPointToRef(point);
  18204. return point;
  18205. };
  18206. /**
  18207. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18208. * Returns the TransformNode.
  18209. */
  18210. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18211. result.x = this._pivotMatrix.m[12];
  18212. result.y = this._pivotMatrix.m[13];
  18213. result.z = this._pivotMatrix.m[14];
  18214. this.getPivotPointToRef(result);
  18215. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18216. return this;
  18217. };
  18218. /**
  18219. * Defines the passed node as the parent of the current node.
  18220. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18221. * Returns the TransformNode.
  18222. */
  18223. TransformNode.prototype.setParent = function (node) {
  18224. if (node === null) {
  18225. var rotation = BABYLON.Tmp.Quaternion[0];
  18226. var position = BABYLON.Tmp.Vector3[0];
  18227. var scale = BABYLON.Tmp.Vector3[1];
  18228. if (this.parent && this.parent.computeWorldMatrix) {
  18229. this.parent.computeWorldMatrix(true);
  18230. }
  18231. this.computeWorldMatrix(true);
  18232. this.getWorldMatrix().decompose(scale, rotation, position);
  18233. if (this.rotationQuaternion) {
  18234. this.rotationQuaternion.copyFrom(rotation);
  18235. }
  18236. else {
  18237. rotation.toEulerAnglesToRef(this.rotation);
  18238. }
  18239. this.scaling.x = scale.x;
  18240. this.scaling.y = scale.y;
  18241. this.scaling.z = scale.z;
  18242. this.position.x = position.x;
  18243. this.position.y = position.y;
  18244. this.position.z = position.z;
  18245. }
  18246. else {
  18247. var rotation = BABYLON.Tmp.Quaternion[0];
  18248. var position = BABYLON.Tmp.Vector3[0];
  18249. var scale = BABYLON.Tmp.Vector3[1];
  18250. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18251. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18252. this.computeWorldMatrix(true);
  18253. node.computeWorldMatrix(true);
  18254. node.getWorldMatrix().invertToRef(invParentMatrix);
  18255. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18256. diffMatrix.decompose(scale, rotation, position);
  18257. if (this.rotationQuaternion) {
  18258. this.rotationQuaternion.copyFrom(rotation);
  18259. }
  18260. else {
  18261. rotation.toEulerAnglesToRef(this.rotation);
  18262. }
  18263. this.position.x = position.x;
  18264. this.position.y = position.y;
  18265. this.position.z = position.z;
  18266. this.scaling.x = scale.x;
  18267. this.scaling.y = scale.y;
  18268. this.scaling.z = scale.z;
  18269. }
  18270. this.parent = node;
  18271. return this;
  18272. };
  18273. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18274. get: function () {
  18275. return this._nonUniformScaling;
  18276. },
  18277. enumerable: true,
  18278. configurable: true
  18279. });
  18280. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18281. if (this._nonUniformScaling === value) {
  18282. return false;
  18283. }
  18284. this._nonUniformScaling = true;
  18285. return true;
  18286. };
  18287. /**
  18288. * Attach the current TransformNode to another TransformNode associated with a bone
  18289. * @param bone Bone affecting the TransformNode
  18290. * @param affectedTransformNode TransformNode associated with the bone
  18291. */
  18292. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18293. this._transformToBoneReferal = affectedTransformNode;
  18294. this.parent = bone;
  18295. if (bone.getWorldMatrix().determinant() < 0) {
  18296. this.scalingDeterminant *= -1;
  18297. }
  18298. return this;
  18299. };
  18300. TransformNode.prototype.detachFromBone = function () {
  18301. if (!this.parent) {
  18302. return this;
  18303. }
  18304. if (this.parent.getWorldMatrix().determinant() < 0) {
  18305. this.scalingDeterminant *= -1;
  18306. }
  18307. this._transformToBoneReferal = null;
  18308. this.parent = null;
  18309. return this;
  18310. };
  18311. /**
  18312. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18313. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18314. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18315. * The passed axis is also normalized.
  18316. * Returns the TransformNode.
  18317. */
  18318. TransformNode.prototype.rotate = function (axis, amount, space) {
  18319. axis.normalize();
  18320. if (!this.rotationQuaternion) {
  18321. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18322. this.rotation = BABYLON.Vector3.Zero();
  18323. }
  18324. var rotationQuaternion;
  18325. if (!space || space === BABYLON.Space.LOCAL) {
  18326. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18327. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18328. }
  18329. else {
  18330. if (this.parent) {
  18331. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18332. invertParentWorldMatrix.invert();
  18333. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18334. }
  18335. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18336. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18337. }
  18338. return this;
  18339. };
  18340. /**
  18341. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18342. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18343. * The passed axis is also normalized.
  18344. * Returns the TransformNode.
  18345. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18346. */
  18347. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18348. axis.normalize();
  18349. if (!this.rotationQuaternion) {
  18350. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18351. this.rotation.copyFromFloats(0, 0, 0);
  18352. }
  18353. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18354. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18355. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18356. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18357. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18358. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18359. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18360. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18361. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18362. return this;
  18363. };
  18364. /**
  18365. * Translates the mesh along the axis vector for the passed distance in the given space.
  18366. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18367. * Returns the TransformNode.
  18368. */
  18369. TransformNode.prototype.translate = function (axis, distance, space) {
  18370. var displacementVector = axis.scale(distance);
  18371. if (!space || space === BABYLON.Space.LOCAL) {
  18372. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18373. this.setPositionWithLocalVector(tempV3);
  18374. }
  18375. else {
  18376. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18377. }
  18378. return this;
  18379. };
  18380. /**
  18381. * Adds a rotation step to the mesh current rotation.
  18382. * x, y, z are Euler angles expressed in radians.
  18383. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18384. * This means this rotation is made in the mesh local space only.
  18385. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18386. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18387. * ```javascript
  18388. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18389. * ```
  18390. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18391. * 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.
  18392. * Returns the TransformNode.
  18393. */
  18394. TransformNode.prototype.addRotation = function (x, y, z) {
  18395. var rotationQuaternion;
  18396. if (this.rotationQuaternion) {
  18397. rotationQuaternion = this.rotationQuaternion;
  18398. }
  18399. else {
  18400. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18401. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18402. }
  18403. var accumulation = BABYLON.Tmp.Quaternion[0];
  18404. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18405. rotationQuaternion.multiplyInPlace(accumulation);
  18406. if (!this.rotationQuaternion) {
  18407. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18408. }
  18409. return this;
  18410. };
  18411. /**
  18412. * Computes the mesh World matrix and returns it.
  18413. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18414. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18415. * If the parameter `force`is set to `true`, the actual computation is done.
  18416. * Returns the mesh World Matrix.
  18417. */
  18418. TransformNode.prototype.computeWorldMatrix = function (force) {
  18419. if (this._isWorldMatrixFrozen) {
  18420. return this._worldMatrix;
  18421. }
  18422. if (!force && this.isSynchronized(true)) {
  18423. this._currentRenderId = this.getScene().getRenderId();
  18424. return this._worldMatrix;
  18425. }
  18426. this._cache.position.copyFrom(this.position);
  18427. this._cache.scaling.copyFrom(this.scaling);
  18428. this._cache.pivotMatrixUpdated = false;
  18429. this._cache.billboardMode = this.billboardMode;
  18430. this._currentRenderId = this.getScene().getRenderId();
  18431. this._childRenderId = this.getScene().getRenderId();
  18432. this._isDirty = false;
  18433. // Scaling
  18434. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18435. // Rotation
  18436. //rotate, if quaternion is set and rotation was used
  18437. if (this.rotationQuaternion) {
  18438. var len = this.rotation.length();
  18439. if (len) {
  18440. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18441. this.rotation.copyFromFloats(0, 0, 0);
  18442. }
  18443. }
  18444. if (this.rotationQuaternion) {
  18445. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18446. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18447. }
  18448. else {
  18449. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18450. this._cache.rotation.copyFrom(this.rotation);
  18451. }
  18452. // Translation
  18453. var camera = this.getScene().activeCamera;
  18454. if (this.infiniteDistance && !this.parent && camera) {
  18455. var cameraWorldMatrix = camera.getWorldMatrix();
  18456. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18457. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18458. }
  18459. else {
  18460. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18461. }
  18462. // Composing transformations
  18463. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18464. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18465. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18466. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18467. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18468. // Need to decompose each rotation here
  18469. var currentPosition = BABYLON.Tmp.Vector3[3];
  18470. if (this.parent && this.parent.getWorldMatrix) {
  18471. if (this._transformToBoneReferal) {
  18472. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18473. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18474. }
  18475. else {
  18476. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18477. }
  18478. }
  18479. else {
  18480. currentPosition.copyFrom(this.position);
  18481. }
  18482. currentPosition.subtractInPlace(camera.globalPosition);
  18483. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18484. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18485. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18486. }
  18487. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18488. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18489. }
  18490. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18491. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18492. }
  18493. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18494. }
  18495. else {
  18496. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18497. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18498. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18499. }
  18500. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18501. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18502. }
  18503. // Local world
  18504. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18505. // Parent
  18506. if (this.parent && this.parent.getWorldMatrix) {
  18507. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18508. if (this._transformToBoneReferal) {
  18509. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18510. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18511. }
  18512. else {
  18513. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18514. }
  18515. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18516. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18517. this._worldMatrix.copyFrom(this._localWorld);
  18518. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18519. }
  18520. else {
  18521. if (this._transformToBoneReferal) {
  18522. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18523. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18524. }
  18525. else {
  18526. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18527. }
  18528. }
  18529. this._markSyncedWithParent();
  18530. }
  18531. else {
  18532. this._worldMatrix.copyFrom(this._localWorld);
  18533. }
  18534. // Post multiply inverse of pivotMatrix
  18535. if (this._postMultiplyPivotMatrix) {
  18536. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18537. }
  18538. // Normal matrix
  18539. if (this.scaling.isNonUniform) {
  18540. this._updateNonUniformScalingState(true);
  18541. }
  18542. else if (this.parent && this.parent._nonUniformScaling) {
  18543. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18544. }
  18545. else {
  18546. this._updateNonUniformScalingState(false);
  18547. }
  18548. this._afterComputeWorldMatrix();
  18549. // Absolute position
  18550. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18551. // Callbacks
  18552. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18553. if (!this._poseMatrix) {
  18554. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18555. }
  18556. // Cache the determinant
  18557. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18558. return this._worldMatrix;
  18559. };
  18560. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18561. };
  18562. /**
  18563. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18564. * @param func: callback function to add
  18565. *
  18566. * Returns the TransformNode.
  18567. */
  18568. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18569. this.onAfterWorldMatrixUpdateObservable.add(func);
  18570. return this;
  18571. };
  18572. /**
  18573. * Removes a registered callback function.
  18574. * Returns the TransformNode.
  18575. */
  18576. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18577. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18578. return this;
  18579. };
  18580. /**
  18581. * Clone the current transform node
  18582. * Returns the new transform node
  18583. * @param name Name of the new clone
  18584. * @param newParent New parent for the clone
  18585. * @param doNotCloneChildren Do not clone children hierarchy
  18586. */
  18587. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18588. var _this = this;
  18589. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18590. result.name = name;
  18591. result.id = name;
  18592. if (newParent) {
  18593. result.parent = newParent;
  18594. }
  18595. if (!doNotCloneChildren) {
  18596. // Children
  18597. var directDescendants = this.getDescendants(true);
  18598. for (var index = 0; index < directDescendants.length; index++) {
  18599. var child = directDescendants[index];
  18600. if (child.clone) {
  18601. child.clone(name + "." + child.name, result);
  18602. }
  18603. }
  18604. }
  18605. return result;
  18606. };
  18607. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18608. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18609. serializationObject.type = this.getClassName();
  18610. // Parent
  18611. if (this.parent) {
  18612. serializationObject.parentId = this.parent.id;
  18613. }
  18614. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18615. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18616. }
  18617. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18618. serializationObject.isEnabled = this.isEnabled();
  18619. // Parent
  18620. if (this.parent) {
  18621. serializationObject.parentId = this.parent.id;
  18622. }
  18623. return serializationObject;
  18624. };
  18625. // Statics
  18626. /**
  18627. * Returns a new TransformNode object parsed from the source provided.
  18628. * The parameter `parsedMesh` is the source.
  18629. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18630. */
  18631. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18632. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18633. if (BABYLON.Tags) {
  18634. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18635. }
  18636. if (parsedTransformNode.localMatrix) {
  18637. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18638. }
  18639. else if (parsedTransformNode.pivotMatrix) {
  18640. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18641. }
  18642. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18643. // Parent
  18644. if (parsedTransformNode.parentId) {
  18645. transformNode._waitingParentId = parsedTransformNode.parentId;
  18646. }
  18647. return transformNode;
  18648. };
  18649. /**
  18650. * Releases resources associated with this transform node.
  18651. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18652. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18653. */
  18654. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18655. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18656. // Animations
  18657. this.getScene().stopAnimation(this);
  18658. // Remove from scene
  18659. this.getScene().removeTransformNode(this);
  18660. this.onAfterWorldMatrixUpdateObservable.clear();
  18661. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18662. };
  18663. // Statics
  18664. TransformNode.BILLBOARDMODE_NONE = 0;
  18665. TransformNode.BILLBOARDMODE_X = 1;
  18666. TransformNode.BILLBOARDMODE_Y = 2;
  18667. TransformNode.BILLBOARDMODE_Z = 4;
  18668. TransformNode.BILLBOARDMODE_ALL = 7;
  18669. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18670. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18671. __decorate([
  18672. BABYLON.serializeAsVector3()
  18673. ], TransformNode.prototype, "_rotation", void 0);
  18674. __decorate([
  18675. BABYLON.serializeAsQuaternion()
  18676. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18677. __decorate([
  18678. BABYLON.serializeAsVector3()
  18679. ], TransformNode.prototype, "_scaling", void 0);
  18680. __decorate([
  18681. BABYLON.serialize()
  18682. ], TransformNode.prototype, "billboardMode", void 0);
  18683. __decorate([
  18684. BABYLON.serialize()
  18685. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18686. __decorate([
  18687. BABYLON.serialize()
  18688. ], TransformNode.prototype, "infiniteDistance", void 0);
  18689. __decorate([
  18690. BABYLON.serializeAsVector3()
  18691. ], TransformNode.prototype, "position", void 0);
  18692. return TransformNode;
  18693. }(BABYLON.Node));
  18694. BABYLON.TransformNode = TransformNode;
  18695. })(BABYLON || (BABYLON = {}));
  18696. //# sourceMappingURL=babylon.transformNode.js.map
  18697. "use strict";
  18698. var BABYLON;
  18699. (function (BABYLON) {
  18700. var AbstractMesh = /** @class */ (function (_super) {
  18701. __extends(AbstractMesh, _super);
  18702. // Constructor
  18703. function AbstractMesh(name, scene) {
  18704. if (scene === void 0) { scene = null; }
  18705. var _this = _super.call(this, name, scene, false) || this;
  18706. _this._facetNb = 0; // facet number
  18707. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18708. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18709. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18710. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18711. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18712. _this._subDiv = {
  18713. max: 1,
  18714. X: 1,
  18715. Y: 1,
  18716. Z: 1
  18717. };
  18718. _this._facetDepthSort = false; // is the facet depth sort to be computed
  18719. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  18720. // Events
  18721. /**
  18722. * An event triggered when this mesh collides with another one
  18723. */
  18724. _this.onCollideObservable = new BABYLON.Observable();
  18725. /**
  18726. * An event triggered when the collision's position changes
  18727. */
  18728. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  18729. /**
  18730. * An event triggered when material is changed
  18731. */
  18732. _this.onMaterialChangedObservable = new BABYLON.Observable();
  18733. // Properties
  18734. _this.definedFacingForward = true; // orientation for POV movement & rotation
  18735. /**
  18736. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  18737. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  18738. * or
  18739. * 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.
  18740. * for more info check WebGl documentations
  18741. */
  18742. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  18743. /**
  18744. * 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:
  18745. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  18746. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  18747. * 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.
  18748. */
  18749. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  18750. /**
  18751. * 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.
  18752. * The default value is -1 which means don't break the query and wait till the result.
  18753. */
  18754. _this.occlusionRetryCount = -1;
  18755. _this._occlusionInternalRetryCounter = 0;
  18756. _this._isOccluded = false;
  18757. _this._isOcclusionQueryInProgress = false;
  18758. _this._visibility = 1.0;
  18759. _this.alphaIndex = Number.MAX_VALUE;
  18760. _this.isVisible = true;
  18761. _this.isPickable = true;
  18762. _this.showBoundingBox = false;
  18763. _this.showSubMeshesBoundingBox = false;
  18764. _this.isBlocker = false;
  18765. _this.enablePointerMoveEvents = false;
  18766. _this.renderingGroupId = 0;
  18767. _this._receiveShadows = false;
  18768. _this.renderOutline = false;
  18769. _this.outlineColor = BABYLON.Color3.Red();
  18770. _this.outlineWidth = 0.02;
  18771. _this.renderOverlay = false;
  18772. _this.overlayColor = BABYLON.Color3.Red();
  18773. _this.overlayAlpha = 0.5;
  18774. _this._hasVertexAlpha = false;
  18775. _this._useVertexColors = true;
  18776. _this._computeBonesUsingShaders = true;
  18777. _this._numBoneInfluencers = 4;
  18778. _this._applyFog = true;
  18779. _this.useOctreeForRenderingSelection = true;
  18780. _this.useOctreeForPicking = true;
  18781. _this.useOctreeForCollisions = true;
  18782. _this._layerMask = 0x0FFFFFFF;
  18783. /**
  18784. * True if the mesh must be rendered in any case.
  18785. */
  18786. _this.alwaysSelectAsActiveMesh = false;
  18787. /**
  18788. * This scene's action manager
  18789. */
  18790. _this.actionManager = null;
  18791. // Physics
  18792. _this.physicsImpostor = null;
  18793. // Collisions
  18794. _this._checkCollisions = false;
  18795. _this._collisionMask = -1;
  18796. _this._collisionGroup = -1;
  18797. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18798. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  18799. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18800. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18801. // Edges
  18802. _this.edgesWidth = 1;
  18803. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  18804. // Cache
  18805. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  18806. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  18807. _this._renderId = 0;
  18808. _this._intersectionsInProgress = new Array();
  18809. _this._unIndexed = false;
  18810. _this._lightSources = new Array();
  18811. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18812. if (collidedMesh === void 0) { collidedMesh = null; }
  18813. //TODO move this to the collision coordinator!
  18814. if (_this.getScene().workerCollisions)
  18815. newPosition.multiplyInPlace(_this._collider._radius);
  18816. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  18817. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  18818. _this.position.addInPlace(_this._diffPositionForCollisions);
  18819. }
  18820. if (collidedMesh) {
  18821. _this.onCollideObservable.notifyObservers(collidedMesh);
  18822. }
  18823. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  18824. };
  18825. _this.getScene().addMesh(_this);
  18826. _this._resyncLightSources();
  18827. return _this;
  18828. }
  18829. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  18830. get: function () {
  18831. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  18832. },
  18833. enumerable: true,
  18834. configurable: true
  18835. });
  18836. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  18837. get: function () {
  18838. return BABYLON.TransformNode.BILLBOARDMODE_X;
  18839. },
  18840. enumerable: true,
  18841. configurable: true
  18842. });
  18843. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  18844. get: function () {
  18845. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  18851. get: function () {
  18852. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  18858. get: function () {
  18859. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  18860. },
  18861. enumerable: true,
  18862. configurable: true
  18863. });
  18864. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  18865. /**
  18866. * Read-only : the number of facets in the mesh
  18867. */
  18868. get: function () {
  18869. return this._facetNb;
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  18875. /**
  18876. * The number (integer) of subdivisions per axis in the partioning space
  18877. */
  18878. get: function () {
  18879. return this._partitioningSubdivisions;
  18880. },
  18881. set: function (nb) {
  18882. this._partitioningSubdivisions = nb;
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  18888. /**
  18889. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  18890. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  18891. */
  18892. get: function () {
  18893. return this._partitioningBBoxRatio;
  18894. },
  18895. set: function (ratio) {
  18896. this._partitioningBBoxRatio = ratio;
  18897. },
  18898. enumerable: true,
  18899. configurable: true
  18900. });
  18901. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  18902. /**
  18903. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  18904. * Works only for updatable meshes.
  18905. * Doesn't work with multi-materials.
  18906. */
  18907. get: function () {
  18908. return this._facetDepthSort;
  18909. },
  18910. set: function (sort) {
  18911. this._facetDepthSort = sort;
  18912. },
  18913. enumerable: true,
  18914. configurable: true
  18915. });
  18916. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  18917. /**
  18918. * The location (Vector3) where the facet depth sort must be computed from.
  18919. * By default, the active camera position.
  18920. * Used only when facet depth sort is enabled.
  18921. */
  18922. get: function () {
  18923. return this._facetDepthSortFrom;
  18924. },
  18925. set: function (location) {
  18926. this._facetDepthSortFrom = location;
  18927. },
  18928. enumerable: true,
  18929. configurable: true
  18930. });
  18931. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  18932. /**
  18933. * Read-only boolean : is the feature facetData enabled ?
  18934. */
  18935. get: function () {
  18936. return this._facetDataEnabled;
  18937. },
  18938. enumerable: true,
  18939. configurable: true
  18940. });
  18941. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  18942. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  18943. return false;
  18944. }
  18945. this._markSubMeshesAsMiscDirty();
  18946. return true;
  18947. };
  18948. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  18949. set: function (callback) {
  18950. if (this._onCollideObserver) {
  18951. this.onCollideObservable.remove(this._onCollideObserver);
  18952. }
  18953. this._onCollideObserver = this.onCollideObservable.add(callback);
  18954. },
  18955. enumerable: true,
  18956. configurable: true
  18957. });
  18958. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  18959. set: function (callback) {
  18960. if (this._onCollisionPositionChangeObserver) {
  18961. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  18962. }
  18963. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  18964. },
  18965. enumerable: true,
  18966. configurable: true
  18967. });
  18968. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  18969. /**
  18970. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  18971. */
  18972. get: function () {
  18973. return this._isOccluded;
  18974. },
  18975. set: function (value) {
  18976. this._isOccluded = value;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  18982. /**
  18983. * Flag to check the progress status of the query
  18984. */
  18985. get: function () {
  18986. return this._isOcclusionQueryInProgress;
  18987. },
  18988. enumerable: true,
  18989. configurable: true
  18990. });
  18991. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  18992. /**
  18993. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  18994. */
  18995. get: function () {
  18996. return this._visibility;
  18997. },
  18998. /**
  18999. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19000. */
  19001. set: function (value) {
  19002. if (this._visibility === value) {
  19003. return;
  19004. }
  19005. this._visibility = value;
  19006. this._markSubMeshesAsMiscDirty();
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Object.defineProperty(AbstractMesh.prototype, "material", {
  19012. get: function () {
  19013. return this._material;
  19014. },
  19015. set: function (value) {
  19016. if (this._material === value) {
  19017. return;
  19018. }
  19019. this._material = value;
  19020. if (this.onMaterialChangedObservable.hasObservers) {
  19021. this.onMaterialChangedObservable.notifyObservers(this);
  19022. }
  19023. if (!this.subMeshes) {
  19024. return;
  19025. }
  19026. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19027. var subMesh = _a[_i];
  19028. subMesh.setEffect(null);
  19029. }
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19035. get: function () {
  19036. return this._receiveShadows;
  19037. },
  19038. set: function (value) {
  19039. if (this._receiveShadows === value) {
  19040. return;
  19041. }
  19042. this._receiveShadows = value;
  19043. this._markSubMeshesAsLightDirty();
  19044. },
  19045. enumerable: true,
  19046. configurable: true
  19047. });
  19048. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19049. get: function () {
  19050. return this._hasVertexAlpha;
  19051. },
  19052. set: function (value) {
  19053. if (this._hasVertexAlpha === value) {
  19054. return;
  19055. }
  19056. this._hasVertexAlpha = value;
  19057. this._markSubMeshesAsAttributesDirty();
  19058. this._markSubMeshesAsMiscDirty();
  19059. },
  19060. enumerable: true,
  19061. configurable: true
  19062. });
  19063. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19064. get: function () {
  19065. return this._useVertexColors;
  19066. },
  19067. set: function (value) {
  19068. if (this._useVertexColors === value) {
  19069. return;
  19070. }
  19071. this._useVertexColors = value;
  19072. this._markSubMeshesAsAttributesDirty();
  19073. },
  19074. enumerable: true,
  19075. configurable: true
  19076. });
  19077. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19078. get: function () {
  19079. return this._computeBonesUsingShaders;
  19080. },
  19081. set: function (value) {
  19082. if (this._computeBonesUsingShaders === value) {
  19083. return;
  19084. }
  19085. this._computeBonesUsingShaders = value;
  19086. this._markSubMeshesAsAttributesDirty();
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19092. get: function () {
  19093. return this._numBoneInfluencers;
  19094. },
  19095. set: function (value) {
  19096. if (this._numBoneInfluencers === value) {
  19097. return;
  19098. }
  19099. this._numBoneInfluencers = value;
  19100. this._markSubMeshesAsAttributesDirty();
  19101. },
  19102. enumerable: true,
  19103. configurable: true
  19104. });
  19105. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19106. get: function () {
  19107. return this._applyFog;
  19108. },
  19109. set: function (value) {
  19110. if (this._applyFog === value) {
  19111. return;
  19112. }
  19113. this._applyFog = value;
  19114. this._markSubMeshesAsMiscDirty();
  19115. },
  19116. enumerable: true,
  19117. configurable: true
  19118. });
  19119. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19120. get: function () {
  19121. return this._layerMask;
  19122. },
  19123. set: function (value) {
  19124. if (value === this._layerMask) {
  19125. return;
  19126. }
  19127. this._layerMask = value;
  19128. this._resyncLightSources();
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19134. get: function () {
  19135. return this._collisionMask;
  19136. },
  19137. set: function (mask) {
  19138. this._collisionMask = !isNaN(mask) ? mask : -1;
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19144. get: function () {
  19145. return this._collisionGroup;
  19146. },
  19147. set: function (mask) {
  19148. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19149. },
  19150. enumerable: true,
  19151. configurable: true
  19152. });
  19153. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19154. get: function () {
  19155. return null;
  19156. },
  19157. enumerable: true,
  19158. configurable: true
  19159. });
  19160. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19161. get: function () {
  19162. return this._skeleton;
  19163. },
  19164. set: function (value) {
  19165. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19166. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19167. }
  19168. if (value && value.needInitialSkinMatrix) {
  19169. value._registerMeshWithPoseMatrix(this);
  19170. }
  19171. this._skeleton = value;
  19172. if (!this._skeleton) {
  19173. this._bonesTransformMatrices = null;
  19174. }
  19175. this._markSubMeshesAsAttributesDirty();
  19176. },
  19177. enumerable: true,
  19178. configurable: true
  19179. });
  19180. /**
  19181. * Returns the string "AbstractMesh"
  19182. */
  19183. AbstractMesh.prototype.getClassName = function () {
  19184. return "AbstractMesh";
  19185. };
  19186. /**
  19187. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19188. */
  19189. AbstractMesh.prototype.toString = function (fullDetails) {
  19190. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19191. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19192. if (this._skeleton) {
  19193. ret += ", skeleton: " + this._skeleton.name;
  19194. }
  19195. if (fullDetails) {
  19196. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19197. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19198. }
  19199. return ret;
  19200. };
  19201. AbstractMesh.prototype._rebuild = function () {
  19202. if (this._occlusionQuery) {
  19203. this._occlusionQuery = null;
  19204. }
  19205. if (this._edgesRenderer) {
  19206. this._edgesRenderer._rebuild();
  19207. }
  19208. if (!this.subMeshes) {
  19209. return;
  19210. }
  19211. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19212. var subMesh = _a[_i];
  19213. subMesh._rebuild();
  19214. }
  19215. };
  19216. AbstractMesh.prototype._resyncLightSources = function () {
  19217. this._lightSources.length = 0;
  19218. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19219. var light = _a[_i];
  19220. if (!light.isEnabled()) {
  19221. continue;
  19222. }
  19223. if (light.canAffectMesh(this)) {
  19224. this._lightSources.push(light);
  19225. }
  19226. }
  19227. this._markSubMeshesAsLightDirty();
  19228. };
  19229. AbstractMesh.prototype._resyncLighSource = function (light) {
  19230. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19231. var index = this._lightSources.indexOf(light);
  19232. if (index === -1) {
  19233. if (!isIn) {
  19234. return;
  19235. }
  19236. this._lightSources.push(light);
  19237. }
  19238. else {
  19239. if (isIn) {
  19240. return;
  19241. }
  19242. this._lightSources.splice(index, 1);
  19243. }
  19244. this._markSubMeshesAsLightDirty();
  19245. };
  19246. AbstractMesh.prototype._removeLightSource = function (light) {
  19247. var index = this._lightSources.indexOf(light);
  19248. if (index === -1) {
  19249. return;
  19250. }
  19251. this._lightSources.splice(index, 1);
  19252. this._markSubMeshesAsLightDirty();
  19253. };
  19254. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19255. if (!this.subMeshes) {
  19256. return;
  19257. }
  19258. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19259. var subMesh = _a[_i];
  19260. if (subMesh._materialDefines) {
  19261. func(subMesh._materialDefines);
  19262. }
  19263. }
  19264. };
  19265. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19266. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19267. };
  19268. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19269. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19270. };
  19271. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19272. if (!this.subMeshes) {
  19273. return;
  19274. }
  19275. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19276. var subMesh = _a[_i];
  19277. var material = subMesh.getMaterial();
  19278. if (material) {
  19279. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19280. }
  19281. }
  19282. };
  19283. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19284. /**
  19285. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19286. * Default : (1.0, 1.0, 1.0)
  19287. */
  19288. get: function () {
  19289. return this._scaling;
  19290. },
  19291. /**
  19292. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19293. * Default : (1.0, 1.0, 1.0)
  19294. */
  19295. set: function (newScaling) {
  19296. this._scaling = newScaling;
  19297. if (this.physicsImpostor) {
  19298. this.physicsImpostor.forceUpdate();
  19299. }
  19300. },
  19301. enumerable: true,
  19302. configurable: true
  19303. });
  19304. // Methods
  19305. /**
  19306. * Disables the mesh edger rendering mode.
  19307. * Returns the AbstractMesh.
  19308. */
  19309. AbstractMesh.prototype.disableEdgesRendering = function () {
  19310. if (this._edgesRenderer) {
  19311. this._edgesRenderer.dispose();
  19312. this._edgesRenderer = null;
  19313. }
  19314. return this;
  19315. };
  19316. /**
  19317. * Enables the edge rendering mode on the mesh.
  19318. * This mode makes the mesh edges visible.
  19319. * Returns the AbstractMesh.
  19320. */
  19321. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19322. if (epsilon === void 0) { epsilon = 0.95; }
  19323. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19324. this.disableEdgesRendering();
  19325. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19326. return this;
  19327. };
  19328. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19329. /**
  19330. * Returns true if the mesh is blocked. Used by the class Mesh.
  19331. * Returns the boolean `false` by default.
  19332. */
  19333. get: function () {
  19334. return false;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. /**
  19340. * Returns the mesh itself by default, used by the class Mesh.
  19341. * Returned type : AbstractMesh
  19342. */
  19343. AbstractMesh.prototype.getLOD = function (camera) {
  19344. return this;
  19345. };
  19346. /**
  19347. * Returns 0 by default, used by the class Mesh.
  19348. * Returns an integer.
  19349. */
  19350. AbstractMesh.prototype.getTotalVertices = function () {
  19351. return 0;
  19352. };
  19353. /**
  19354. * Returns null by default, used by the class Mesh.
  19355. * Returned type : integer array
  19356. */
  19357. AbstractMesh.prototype.getIndices = function () {
  19358. return null;
  19359. };
  19360. /**
  19361. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19362. * Returned type : float array or Float32Array
  19363. */
  19364. AbstractMesh.prototype.getVerticesData = function (kind) {
  19365. return null;
  19366. };
  19367. /**
  19368. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19369. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19370. * The `data` are either a numeric array either a Float32Array.
  19371. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19372. * 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).
  19373. * Note that a new underlying VertexBuffer object is created each call.
  19374. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19375. *
  19376. * Possible `kind` values :
  19377. * - BABYLON.VertexBuffer.PositionKind
  19378. * - BABYLON.VertexBuffer.UVKind
  19379. * - BABYLON.VertexBuffer.UV2Kind
  19380. * - BABYLON.VertexBuffer.UV3Kind
  19381. * - BABYLON.VertexBuffer.UV4Kind
  19382. * - BABYLON.VertexBuffer.UV5Kind
  19383. * - BABYLON.VertexBuffer.UV6Kind
  19384. * - BABYLON.VertexBuffer.ColorKind
  19385. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19386. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19387. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19388. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19389. *
  19390. * Returns the Mesh.
  19391. */
  19392. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19393. return this;
  19394. };
  19395. /**
  19396. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19397. * If the mesh has no geometry, it is simply returned as it is.
  19398. * The `data` are either a numeric array either a Float32Array.
  19399. * No new underlying VertexBuffer object is created.
  19400. * 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.
  19401. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19402. *
  19403. * Possible `kind` values :
  19404. * - BABYLON.VertexBuffer.PositionKind
  19405. * - BABYLON.VertexBuffer.UVKind
  19406. * - BABYLON.VertexBuffer.UV2Kind
  19407. * - BABYLON.VertexBuffer.UV3Kind
  19408. * - BABYLON.VertexBuffer.UV4Kind
  19409. * - BABYLON.VertexBuffer.UV5Kind
  19410. * - BABYLON.VertexBuffer.UV6Kind
  19411. * - BABYLON.VertexBuffer.ColorKind
  19412. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19413. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19414. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19415. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19416. *
  19417. * Returns the Mesh.
  19418. */
  19419. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19420. return this;
  19421. };
  19422. /**
  19423. * Sets the mesh indices.
  19424. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19425. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19426. * This method creates a new index buffer each call.
  19427. * Returns the Mesh.
  19428. */
  19429. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19430. return this;
  19431. };
  19432. /** Returns false by default, used by the class Mesh.
  19433. * Returns a boolean
  19434. */
  19435. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19436. return false;
  19437. };
  19438. /**
  19439. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19440. * Returns a BoundingInfo
  19441. */
  19442. AbstractMesh.prototype.getBoundingInfo = function () {
  19443. if (this._masterMesh) {
  19444. return this._masterMesh.getBoundingInfo();
  19445. }
  19446. if (!this._boundingInfo) {
  19447. // this._boundingInfo is being created here
  19448. this._updateBoundingInfo();
  19449. }
  19450. // cannot be null.
  19451. return this._boundingInfo;
  19452. };
  19453. /**
  19454. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19455. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19456. */
  19457. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19458. if (includeDescendants === void 0) { includeDescendants = true; }
  19459. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19460. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19461. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19462. if (maxDimension === 0) {
  19463. return this;
  19464. }
  19465. var scale = 1 / maxDimension;
  19466. this.scaling.scaleInPlace(scale);
  19467. return this;
  19468. };
  19469. /**
  19470. * Sets a mesh new object BoundingInfo.
  19471. * Returns the AbstractMesh.
  19472. */
  19473. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19474. this._boundingInfo = boundingInfo;
  19475. return this;
  19476. };
  19477. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19478. get: function () {
  19479. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. AbstractMesh.prototype._preActivate = function () {
  19485. };
  19486. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19487. };
  19488. AbstractMesh.prototype._activate = function (renderId) {
  19489. this._renderId = renderId;
  19490. };
  19491. /**
  19492. * Returns the latest update of the World matrix
  19493. * Returns a Matrix.
  19494. */
  19495. AbstractMesh.prototype.getWorldMatrix = function () {
  19496. if (this._masterMesh) {
  19497. return this._masterMesh.getWorldMatrix();
  19498. }
  19499. return _super.prototype.getWorldMatrix.call(this);
  19500. };
  19501. /**
  19502. * Returns the latest update of the World matrix determinant.
  19503. */
  19504. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19505. if (this._masterMesh) {
  19506. return this._masterMesh._getWorldMatrixDeterminant();
  19507. }
  19508. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19509. };
  19510. // ================================== Point of View Movement =================================
  19511. /**
  19512. * Perform relative position change from the point of view of behind the front of the mesh.
  19513. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19514. * Supports definition of mesh facing forward or backward.
  19515. * @param {number} amountRight
  19516. * @param {number} amountUp
  19517. * @param {number} amountForward
  19518. *
  19519. * Returns the AbstractMesh.
  19520. */
  19521. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19522. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19523. return this;
  19524. };
  19525. /**
  19526. * Calculate relative position change from the point of view of behind the front of the mesh.
  19527. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19528. * Supports definition of mesh facing forward or backward.
  19529. * @param {number} amountRight
  19530. * @param {number} amountUp
  19531. * @param {number} amountForward
  19532. *
  19533. * Returns a new Vector3.
  19534. */
  19535. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19536. var rotMatrix = new BABYLON.Matrix();
  19537. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19538. rotQuaternion.toRotationMatrix(rotMatrix);
  19539. var translationDelta = BABYLON.Vector3.Zero();
  19540. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19541. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19542. return translationDelta;
  19543. };
  19544. // ================================== Point of View Rotation =================================
  19545. /**
  19546. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19547. * Supports definition of mesh facing forward or backward.
  19548. * @param {number} flipBack
  19549. * @param {number} twirlClockwise
  19550. * @param {number} tiltRight
  19551. *
  19552. * Returns the AbstractMesh.
  19553. */
  19554. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19555. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19556. return this;
  19557. };
  19558. /**
  19559. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19560. * Supports definition of mesh facing forward or backward.
  19561. * @param {number} flipBack
  19562. * @param {number} twirlClockwise
  19563. * @param {number} tiltRight
  19564. *
  19565. * Returns a new Vector3.
  19566. */
  19567. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19568. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19569. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19570. };
  19571. /**
  19572. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19573. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19574. */
  19575. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19576. if (includeDescendants === void 0) { includeDescendants = true; }
  19577. this.computeWorldMatrix(true);
  19578. var min;
  19579. var max;
  19580. var boundingInfo = this.getBoundingInfo();
  19581. if (!this.subMeshes) {
  19582. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19583. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19584. }
  19585. else {
  19586. min = boundingInfo.boundingBox.minimumWorld;
  19587. max = boundingInfo.boundingBox.maximumWorld;
  19588. }
  19589. if (includeDescendants) {
  19590. var descendants = this.getDescendants(false);
  19591. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19592. var descendant = descendants_1[_i];
  19593. var childMesh = descendant;
  19594. childMesh.computeWorldMatrix(true);
  19595. //make sure we have the needed params to get mix and max
  19596. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19597. continue;
  19598. }
  19599. var childBoundingInfo = childMesh.getBoundingInfo();
  19600. var boundingBox = childBoundingInfo.boundingBox;
  19601. var minBox = boundingBox.minimumWorld;
  19602. var maxBox = boundingBox.maximumWorld;
  19603. BABYLON.Tools.CheckExtends(minBox, min, max);
  19604. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19605. }
  19606. }
  19607. return {
  19608. min: min,
  19609. max: max
  19610. };
  19611. };
  19612. /**
  19613. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19614. * Returns the AbstractMesh.
  19615. */
  19616. AbstractMesh.prototype._updateBoundingInfo = function () {
  19617. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19618. this._boundingInfo.update(this.worldMatrixFromCache);
  19619. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19620. return this;
  19621. };
  19622. /**
  19623. * Update a mesh's children BoundingInfo objects only.
  19624. * Returns the AbstractMesh.
  19625. */
  19626. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19627. if (!this.subMeshes) {
  19628. return this;
  19629. }
  19630. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19631. var subMesh = this.subMeshes[subIndex];
  19632. if (!subMesh.IsGlobal) {
  19633. subMesh.updateBoundingInfo(matrix);
  19634. }
  19635. }
  19636. return this;
  19637. };
  19638. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19639. // Bounding info
  19640. this._updateBoundingInfo();
  19641. };
  19642. /**
  19643. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19644. * A mesh is in the frustum if its bounding box intersects the frustum.
  19645. * Boolean returned.
  19646. */
  19647. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19648. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19649. };
  19650. /**
  19651. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19652. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19653. * Boolean returned.
  19654. */
  19655. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19656. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19657. ;
  19658. };
  19659. /**
  19660. * True if the mesh intersects another mesh or a SolidParticle object.
  19661. * 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)
  19662. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19663. * Returns a boolean.
  19664. */
  19665. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19666. if (precise === void 0) { precise = false; }
  19667. if (!this._boundingInfo || !mesh._boundingInfo) {
  19668. return false;
  19669. }
  19670. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19671. return true;
  19672. }
  19673. if (includeDescendants) {
  19674. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19675. var child = _a[_i];
  19676. if (child.intersectsMesh(mesh, precise, true)) {
  19677. return true;
  19678. }
  19679. }
  19680. }
  19681. return false;
  19682. };
  19683. /**
  19684. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19685. * Returns a boolean.
  19686. */
  19687. AbstractMesh.prototype.intersectsPoint = function (point) {
  19688. if (!this._boundingInfo) {
  19689. return false;
  19690. }
  19691. return this._boundingInfo.intersectsPoint(point);
  19692. };
  19693. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19694. return this.physicsImpostor;
  19695. };
  19696. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19697. if (camera === void 0) { camera = null; }
  19698. if (!camera) {
  19699. camera = this.getScene().activeCamera;
  19700. }
  19701. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19702. };
  19703. /**
  19704. * Returns the distance from the mesh to the active camera.
  19705. * Returns a float.
  19706. */
  19707. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19708. if (camera === void 0) { camera = null; }
  19709. if (!camera) {
  19710. camera = this.getScene().activeCamera;
  19711. }
  19712. return this.absolutePosition.subtract(camera.position).length();
  19713. };
  19714. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19715. if (!this.physicsImpostor) {
  19716. return this;
  19717. }
  19718. this.physicsImpostor.applyImpulse(force, contactPoint);
  19719. return this;
  19720. };
  19721. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  19722. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  19723. return this;
  19724. }
  19725. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  19726. mainPivot: pivot1,
  19727. connectedPivot: pivot2,
  19728. nativeParams: options
  19729. });
  19730. return this;
  19731. };
  19732. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  19733. // Collisions
  19734. /**
  19735. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  19736. * Default `false`.
  19737. */
  19738. get: function () {
  19739. return this._checkCollisions;
  19740. },
  19741. set: function (collisionEnabled) {
  19742. this._checkCollisions = collisionEnabled;
  19743. if (this.getScene().workerCollisions) {
  19744. this.getScene().collisionCoordinator.onMeshUpdated(this);
  19745. }
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Object.defineProperty(AbstractMesh.prototype, "collider", {
  19751. /**
  19752. * Gets Collider object used to compute collisions (not physics)
  19753. */
  19754. get: function () {
  19755. return this._collider;
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  19761. var globalPosition = this.getAbsolutePosition();
  19762. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  19763. if (!this._collider) {
  19764. this._collider = new BABYLON.Collider();
  19765. }
  19766. this._collider._radius = this.ellipsoid;
  19767. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  19768. return this;
  19769. };
  19770. // Submeshes octree
  19771. /**
  19772. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  19773. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  19774. * Returns an Octree of submeshes.
  19775. */
  19776. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  19777. if (maxCapacity === void 0) { maxCapacity = 64; }
  19778. if (maxDepth === void 0) { maxDepth = 2; }
  19779. if (!this._submeshesOctree) {
  19780. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  19781. }
  19782. this.computeWorldMatrix(true);
  19783. var boundingInfo = this.getBoundingInfo();
  19784. // Update octree
  19785. var bbox = boundingInfo.boundingBox;
  19786. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  19787. return this._submeshesOctree;
  19788. };
  19789. // Collisions
  19790. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  19791. this._generatePointsArray();
  19792. if (!this._positions) {
  19793. return this;
  19794. }
  19795. // Transformation
  19796. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  19797. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  19798. subMesh._lastColliderWorldVertices = [];
  19799. subMesh._trianglePlanes = [];
  19800. var start = subMesh.verticesStart;
  19801. var end = (subMesh.verticesStart + subMesh.verticesCount);
  19802. for (var i = start; i < end; i++) {
  19803. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  19804. }
  19805. }
  19806. // Collide
  19807. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  19808. if (collider.collisionFound) {
  19809. collider.collidedMesh = this;
  19810. }
  19811. return this;
  19812. };
  19813. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  19814. var subMeshes;
  19815. var len;
  19816. // Octrees
  19817. if (this._submeshesOctree && this.useOctreeForCollisions) {
  19818. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  19819. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  19820. len = intersections.length;
  19821. subMeshes = intersections.data;
  19822. }
  19823. else {
  19824. subMeshes = this.subMeshes;
  19825. len = subMeshes.length;
  19826. }
  19827. for (var index = 0; index < len; index++) {
  19828. var subMesh = subMeshes[index];
  19829. // Bounding test
  19830. if (len > 1 && !subMesh._checkCollision(collider))
  19831. continue;
  19832. this._collideForSubMesh(subMesh, transformMatrix, collider);
  19833. }
  19834. return this;
  19835. };
  19836. AbstractMesh.prototype._checkCollision = function (collider) {
  19837. // Bounding box test
  19838. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  19839. return this;
  19840. // Transformation matrix
  19841. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  19842. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  19843. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  19844. return this;
  19845. };
  19846. // Picking
  19847. AbstractMesh.prototype._generatePointsArray = function () {
  19848. return false;
  19849. };
  19850. /**
  19851. * Checks if the passed Ray intersects with the mesh.
  19852. * Returns an object PickingInfo.
  19853. */
  19854. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  19855. var pickingInfo = new BABYLON.PickingInfo();
  19856. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  19857. return pickingInfo;
  19858. }
  19859. if (!this._generatePointsArray()) {
  19860. return pickingInfo;
  19861. }
  19862. var intersectInfo = null;
  19863. // Octrees
  19864. var subMeshes;
  19865. var len;
  19866. if (this._submeshesOctree && this.useOctreeForPicking) {
  19867. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  19868. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  19869. len = intersections.length;
  19870. subMeshes = intersections.data;
  19871. }
  19872. else {
  19873. subMeshes = this.subMeshes;
  19874. len = subMeshes.length;
  19875. }
  19876. for (var index = 0; index < len; index++) {
  19877. var subMesh = subMeshes[index];
  19878. // Bounding test
  19879. if (len > 1 && !subMesh.canIntersects(ray))
  19880. continue;
  19881. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  19882. if (currentIntersectInfo) {
  19883. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19884. intersectInfo = currentIntersectInfo;
  19885. intersectInfo.subMeshId = index;
  19886. if (fastCheck) {
  19887. break;
  19888. }
  19889. }
  19890. }
  19891. }
  19892. if (intersectInfo) {
  19893. // Get picked point
  19894. var world = this.getWorldMatrix();
  19895. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  19896. var direction = ray.direction.clone();
  19897. direction = direction.scale(intersectInfo.distance);
  19898. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  19899. var pickedPoint = worldOrigin.add(worldDirection);
  19900. // Return result
  19901. pickingInfo.hit = true;
  19902. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  19903. pickingInfo.pickedPoint = pickedPoint;
  19904. pickingInfo.pickedMesh = this;
  19905. pickingInfo.bu = intersectInfo.bu || 0;
  19906. pickingInfo.bv = intersectInfo.bv || 0;
  19907. pickingInfo.faceId = intersectInfo.faceId;
  19908. pickingInfo.subMeshId = intersectInfo.subMeshId;
  19909. return pickingInfo;
  19910. }
  19911. return pickingInfo;
  19912. };
  19913. /**
  19914. * Clones the mesh, used by the class Mesh.
  19915. * Just returns `null` for an AbstractMesh.
  19916. */
  19917. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19918. return null;
  19919. };
  19920. /**
  19921. * Disposes all the mesh submeshes.
  19922. * Returns the AbstractMesh.
  19923. */
  19924. AbstractMesh.prototype.releaseSubMeshes = function () {
  19925. if (this.subMeshes) {
  19926. while (this.subMeshes.length) {
  19927. this.subMeshes[0].dispose();
  19928. }
  19929. }
  19930. else {
  19931. this.subMeshes = new Array();
  19932. }
  19933. return this;
  19934. };
  19935. /**
  19936. * Releases resources associated with this abstract mesh.
  19937. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19938. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19939. */
  19940. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19941. var _this = this;
  19942. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19943. var index;
  19944. // Smart Array Retainers.
  19945. this.getScene().freeActiveMeshes();
  19946. this.getScene().freeRenderingGroups();
  19947. // Action manager
  19948. if (this.actionManager !== undefined && this.actionManager !== null) {
  19949. this.actionManager.dispose();
  19950. this.actionManager = null;
  19951. }
  19952. // Skeleton
  19953. this._skeleton = null;
  19954. // Physics
  19955. if (this.physicsImpostor) {
  19956. this.physicsImpostor.dispose();
  19957. }
  19958. // Intersections in progress
  19959. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  19960. var other = this._intersectionsInProgress[index];
  19961. var pos = other._intersectionsInProgress.indexOf(this);
  19962. other._intersectionsInProgress.splice(pos, 1);
  19963. }
  19964. this._intersectionsInProgress = [];
  19965. // Lights
  19966. var lights = this.getScene().lights;
  19967. lights.forEach(function (light) {
  19968. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  19969. if (meshIndex !== -1) {
  19970. light.includedOnlyMeshes.splice(meshIndex, 1);
  19971. }
  19972. meshIndex = light.excludedMeshes.indexOf(_this);
  19973. if (meshIndex !== -1) {
  19974. light.excludedMeshes.splice(meshIndex, 1);
  19975. }
  19976. // Shadow generators
  19977. var generator = light.getShadowGenerator();
  19978. if (generator) {
  19979. var shadowMap = generator.getShadowMap();
  19980. if (shadowMap && shadowMap.renderList) {
  19981. meshIndex = shadowMap.renderList.indexOf(_this);
  19982. if (meshIndex !== -1) {
  19983. shadowMap.renderList.splice(meshIndex, 1);
  19984. }
  19985. }
  19986. }
  19987. });
  19988. // Edges
  19989. if (this._edgesRenderer) {
  19990. this._edgesRenderer.dispose();
  19991. this._edgesRenderer = null;
  19992. }
  19993. // SubMeshes
  19994. if (this.getClassName() !== "InstancedMesh") {
  19995. this.releaseSubMeshes();
  19996. }
  19997. // Octree
  19998. var sceneOctree = this.getScene().selectionOctree;
  19999. if (sceneOctree !== undefined && sceneOctree !== null) {
  20000. var index = sceneOctree.dynamicContent.indexOf(this);
  20001. if (index !== -1) {
  20002. sceneOctree.dynamicContent.splice(index, 1);
  20003. }
  20004. }
  20005. // Query
  20006. var engine = this.getScene().getEngine();
  20007. if (this._occlusionQuery) {
  20008. this._isOcclusionQueryInProgress = false;
  20009. engine.deleteQuery(this._occlusionQuery);
  20010. this._occlusionQuery = null;
  20011. }
  20012. // Engine
  20013. engine.wipeCaches();
  20014. // Remove from scene
  20015. this.getScene().removeMesh(this);
  20016. if (disposeMaterialAndTextures) {
  20017. if (this.material) {
  20018. this.material.dispose(false, true);
  20019. }
  20020. }
  20021. if (!doNotRecurse) {
  20022. // Particles
  20023. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20024. if (this.getScene().particleSystems[index].emitter === this) {
  20025. this.getScene().particleSystems[index].dispose();
  20026. index--;
  20027. }
  20028. }
  20029. }
  20030. // facet data
  20031. if (this._facetDataEnabled) {
  20032. this.disableFacetData();
  20033. }
  20034. this.onAfterWorldMatrixUpdateObservable.clear();
  20035. this.onCollideObservable.clear();
  20036. this.onCollisionPositionChangeObservable.clear();
  20037. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20038. };
  20039. /**
  20040. * Adds the passed mesh as a child to the current mesh.
  20041. * Returns the AbstractMesh.
  20042. */
  20043. AbstractMesh.prototype.addChild = function (mesh) {
  20044. mesh.setParent(this);
  20045. return this;
  20046. };
  20047. /**
  20048. * Removes the passed mesh from the current mesh children list.
  20049. * Returns the AbstractMesh.
  20050. */
  20051. AbstractMesh.prototype.removeChild = function (mesh) {
  20052. mesh.setParent(null);
  20053. return this;
  20054. };
  20055. // Facet data
  20056. /**
  20057. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20058. * Returns the AbstractMesh.
  20059. */
  20060. AbstractMesh.prototype._initFacetData = function () {
  20061. if (!this._facetNormals) {
  20062. this._facetNormals = new Array();
  20063. }
  20064. if (!this._facetPositions) {
  20065. this._facetPositions = new Array();
  20066. }
  20067. if (!this._facetPartitioning) {
  20068. this._facetPartitioning = new Array();
  20069. }
  20070. this._facetNb = (this.getIndices().length / 3) | 0;
  20071. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20072. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20073. for (var f = 0; f < this._facetNb; f++) {
  20074. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20075. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20076. }
  20077. this._facetDataEnabled = true;
  20078. return this;
  20079. };
  20080. /**
  20081. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20082. * This method can be called within the render loop.
  20083. * 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.
  20084. * Returns the AbstractMesh.
  20085. */
  20086. AbstractMesh.prototype.updateFacetData = function () {
  20087. if (!this._facetDataEnabled) {
  20088. this._initFacetData();
  20089. }
  20090. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20091. var indices = this.getIndices();
  20092. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20093. var bInfo = this.getBoundingInfo();
  20094. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20095. // init arrays, matrix and sort function on first call
  20096. this._facetDepthSortEnabled = true;
  20097. if (indices instanceof Uint16Array) {
  20098. this._depthSortedIndices = new Uint16Array(indices);
  20099. }
  20100. else if (indices instanceof Uint32Array) {
  20101. this._depthSortedIndices = new Uint32Array(indices);
  20102. }
  20103. else {
  20104. var needs32bits = false;
  20105. for (var i = 0; i < indices.length; i++) {
  20106. if (indices[i] > 65535) {
  20107. needs32bits = true;
  20108. break;
  20109. }
  20110. }
  20111. if (needs32bits) {
  20112. this._depthSortedIndices = new Uint32Array(indices);
  20113. }
  20114. else {
  20115. this._depthSortedIndices = new Uint16Array(indices);
  20116. }
  20117. }
  20118. this._facetDepthSortFunction = function (f1, f2) {
  20119. return (f2.sqDistance - f1.sqDistance);
  20120. };
  20121. if (!this._facetDepthSortFrom) {
  20122. var camera = this.getScene().activeCamera;
  20123. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20124. }
  20125. this._depthSortedFacets = [];
  20126. for (var f = 0; f < this._facetNb; f++) {
  20127. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20128. this._depthSortedFacets.push(depthSortedFacet);
  20129. }
  20130. this._invertedMatrix = BABYLON.Matrix.Identity();
  20131. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20132. }
  20133. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20134. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20135. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20136. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20137. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20138. this._subDiv.max = this._partitioningSubdivisions;
  20139. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20140. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20141. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20142. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20143. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20144. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20145. // set the parameters for ComputeNormals()
  20146. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20147. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20148. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20149. this._facetParameters.bInfo = bInfo;
  20150. this._facetParameters.bbSize = this._bbSize;
  20151. this._facetParameters.subDiv = this._subDiv;
  20152. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20153. this._facetParameters.depthSort = this._facetDepthSort;
  20154. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20155. this.computeWorldMatrix(true);
  20156. this._worldMatrix.invertToRef(this._invertedMatrix);
  20157. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20158. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20159. }
  20160. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20161. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20162. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20163. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20164. var l = (this._depthSortedIndices.length / 3) | 0;
  20165. for (var f = 0; f < l; f++) {
  20166. var sind = this._depthSortedFacets[f].ind;
  20167. this._depthSortedIndices[f * 3] = indices[sind];
  20168. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20169. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20170. }
  20171. this.updateIndices(this._depthSortedIndices);
  20172. }
  20173. return this;
  20174. };
  20175. /**
  20176. * Returns the facetLocalNormals array.
  20177. * The normals are expressed in the mesh local space.
  20178. */
  20179. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20180. if (!this._facetNormals) {
  20181. this.updateFacetData();
  20182. }
  20183. return this._facetNormals;
  20184. };
  20185. /**
  20186. * Returns the facetLocalPositions array.
  20187. * The facet positions are expressed in the mesh local space.
  20188. */
  20189. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20190. if (!this._facetPositions) {
  20191. this.updateFacetData();
  20192. }
  20193. return this._facetPositions;
  20194. };
  20195. /**
  20196. * Returns the facetLocalPartioning array.
  20197. */
  20198. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20199. if (!this._facetPartitioning) {
  20200. this.updateFacetData();
  20201. }
  20202. return this._facetPartitioning;
  20203. };
  20204. /**
  20205. * Returns the i-th facet position in the world system.
  20206. * This method allocates a new Vector3 per call.
  20207. */
  20208. AbstractMesh.prototype.getFacetPosition = function (i) {
  20209. var pos = BABYLON.Vector3.Zero();
  20210. this.getFacetPositionToRef(i, pos);
  20211. return pos;
  20212. };
  20213. /**
  20214. * Sets the reference Vector3 with the i-th facet position in the world system.
  20215. * Returns the AbstractMesh.
  20216. */
  20217. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20218. var localPos = (this.getFacetLocalPositions())[i];
  20219. var world = this.getWorldMatrix();
  20220. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20221. return this;
  20222. };
  20223. /**
  20224. * Returns the i-th facet normal in the world system.
  20225. * This method allocates a new Vector3 per call.
  20226. */
  20227. AbstractMesh.prototype.getFacetNormal = function (i) {
  20228. var norm = BABYLON.Vector3.Zero();
  20229. this.getFacetNormalToRef(i, norm);
  20230. return norm;
  20231. };
  20232. /**
  20233. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20234. * Returns the AbstractMesh.
  20235. */
  20236. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20237. var localNorm = (this.getFacetLocalNormals())[i];
  20238. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20239. return this;
  20240. };
  20241. /**
  20242. * 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).
  20243. */
  20244. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20245. var bInfo = this.getBoundingInfo();
  20246. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20247. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20248. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20249. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20250. return null;
  20251. }
  20252. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20253. };
  20254. /**
  20255. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20256. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20257. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  20258. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20259. * 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.
  20260. */
  20261. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20262. if (checkFace === void 0) { checkFace = false; }
  20263. if (facing === void 0) { facing = true; }
  20264. var world = this.getWorldMatrix();
  20265. var invMat = BABYLON.Tmp.Matrix[5];
  20266. world.invertToRef(invMat);
  20267. var invVect = BABYLON.Tmp.Vector3[8];
  20268. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20269. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20270. if (projected) {
  20271. // tranform the local computed projected vector to world coordinates
  20272. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20273. }
  20274. return closest;
  20275. };
  20276. /**
  20277. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20278. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20279. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  20280. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20281. * 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.
  20282. */
  20283. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20284. if (checkFace === void 0) { checkFace = false; }
  20285. if (facing === void 0) { facing = true; }
  20286. var closest = null;
  20287. var tmpx = 0.0;
  20288. var tmpy = 0.0;
  20289. var tmpz = 0.0;
  20290. var d = 0.0; // tmp dot facet normal * facet position
  20291. var t0 = 0.0;
  20292. var projx = 0.0;
  20293. var projy = 0.0;
  20294. var projz = 0.0;
  20295. // Get all the facets in the same partitioning block than (x, y, z)
  20296. var facetPositions = this.getFacetLocalPositions();
  20297. var facetNormals = this.getFacetLocalNormals();
  20298. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20299. if (!facetsInBlock) {
  20300. return null;
  20301. }
  20302. // Get the closest facet to (x, y, z)
  20303. var shortest = Number.MAX_VALUE; // init distance vars
  20304. var tmpDistance = shortest;
  20305. var fib; // current facet in the block
  20306. var norm; // current facet normal
  20307. var p0; // current facet barycenter position
  20308. // loop on all the facets in the current partitioning block
  20309. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20310. fib = facetsInBlock[idx];
  20311. norm = facetNormals[fib];
  20312. p0 = facetPositions[fib];
  20313. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20314. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20315. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20316. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20317. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20318. projx = x + norm.x * t0;
  20319. projy = y + norm.y * t0;
  20320. projz = z + norm.z * t0;
  20321. tmpx = projx - x;
  20322. tmpy = projy - y;
  20323. tmpz = projz - z;
  20324. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20325. if (tmpDistance < shortest) {
  20326. shortest = tmpDistance;
  20327. closest = fib;
  20328. if (projected) {
  20329. projected.x = projx;
  20330. projected.y = projy;
  20331. projected.z = projz;
  20332. }
  20333. }
  20334. }
  20335. }
  20336. return closest;
  20337. };
  20338. /**
  20339. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20340. */
  20341. AbstractMesh.prototype.getFacetDataParameters = function () {
  20342. return this._facetParameters;
  20343. };
  20344. /**
  20345. * Disables the feature FacetData and frees the related memory.
  20346. * Returns the AbstractMesh.
  20347. */
  20348. AbstractMesh.prototype.disableFacetData = function () {
  20349. if (this._facetDataEnabled) {
  20350. this._facetDataEnabled = false;
  20351. this._facetPositions = new Array();
  20352. this._facetNormals = new Array();
  20353. this._facetPartitioning = new Array();
  20354. this._facetParameters = null;
  20355. this._depthSortedIndices = new Uint32Array(0);
  20356. }
  20357. return this;
  20358. };
  20359. /**
  20360. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20361. * Returns the mesh.
  20362. */
  20363. AbstractMesh.prototype.updateIndices = function (indices) {
  20364. return this;
  20365. };
  20366. /**
  20367. * The mesh Geometry. Actually used by the Mesh object.
  20368. * Returns a blank geometry object.
  20369. */
  20370. /**
  20371. * Creates new normals data for the mesh.
  20372. * @param updatable.
  20373. */
  20374. AbstractMesh.prototype.createNormals = function (updatable) {
  20375. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20376. var indices = this.getIndices();
  20377. var normals;
  20378. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20379. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20380. }
  20381. else {
  20382. normals = [];
  20383. }
  20384. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20385. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20386. };
  20387. /**
  20388. * Align the mesh with a normal.
  20389. * Returns the mesh.
  20390. */
  20391. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20392. if (!upDirection) {
  20393. upDirection = BABYLON.Axis.Y;
  20394. }
  20395. var axisX = BABYLON.Tmp.Vector3[0];
  20396. var axisZ = BABYLON.Tmp.Vector3[1];
  20397. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20398. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20399. if (this.rotationQuaternion) {
  20400. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20401. }
  20402. else {
  20403. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20404. }
  20405. return this;
  20406. };
  20407. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20408. var engine = this.getEngine();
  20409. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20410. this._isOccluded = false;
  20411. return;
  20412. }
  20413. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20414. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20415. if (isOcclusionQueryAvailable) {
  20416. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20417. this._isOcclusionQueryInProgress = false;
  20418. this._occlusionInternalRetryCounter = 0;
  20419. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20420. }
  20421. else {
  20422. this._occlusionInternalRetryCounter++;
  20423. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20424. this._isOcclusionQueryInProgress = false;
  20425. this._occlusionInternalRetryCounter = 0;
  20426. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20427. // if strict continue the last state of the object.
  20428. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20429. }
  20430. else {
  20431. return;
  20432. }
  20433. }
  20434. }
  20435. var scene = this.getScene();
  20436. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20437. if (!this._occlusionQuery) {
  20438. this._occlusionQuery = engine.createQuery();
  20439. }
  20440. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20441. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20442. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20443. this._isOcclusionQueryInProgress = true;
  20444. };
  20445. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20446. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20447. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20448. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20449. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20450. return AbstractMesh;
  20451. }(BABYLON.TransformNode));
  20452. BABYLON.AbstractMesh = AbstractMesh;
  20453. })(BABYLON || (BABYLON = {}));
  20454. //# sourceMappingURL=babylon.abstractMesh.js.map
  20455. "use strict";
  20456. var BABYLON;
  20457. (function (BABYLON) {
  20458. /**
  20459. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20460. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20461. * 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.
  20462. */
  20463. var Light = /** @class */ (function (_super) {
  20464. __extends(Light, _super);
  20465. /**
  20466. * Creates a Light object in the scene.
  20467. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20468. * @param name The firendly name of the light
  20469. * @param scene The scene the light belongs too
  20470. */
  20471. function Light(name, scene) {
  20472. var _this = _super.call(this, name, scene) || this;
  20473. /**
  20474. * Diffuse gives the basic color to an object.
  20475. */
  20476. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20477. /**
  20478. * Specular produces a highlight color on an object.
  20479. * Note: This is note affecting PBR materials.
  20480. */
  20481. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20482. /**
  20483. * Strength of the light.
  20484. * Note: By default it is define in the framework own unit.
  20485. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20486. */
  20487. _this.intensity = 1.0;
  20488. /**
  20489. * Defines how far from the source the light is impacting in scene units.
  20490. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20491. */
  20492. _this.range = Number.MAX_VALUE;
  20493. /**
  20494. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20495. * of light.
  20496. */
  20497. _this._photometricScale = 1.0;
  20498. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20499. _this._radius = 0.00001;
  20500. /**
  20501. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20502. * exceeding the number allowed of the materials.
  20503. */
  20504. _this.renderPriority = 0;
  20505. /**
  20506. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20507. * the current shadow generator.
  20508. */
  20509. _this.shadowEnabled = true;
  20510. _this._excludeWithLayerMask = 0;
  20511. _this._includeOnlyWithLayerMask = 0;
  20512. _this._lightmapMode = 0;
  20513. /**
  20514. * @ignore Internal use only.
  20515. */
  20516. _this._excludedMeshesIds = new Array();
  20517. /**
  20518. * @ignore Internal use only.
  20519. */
  20520. _this._includedOnlyMeshesIds = new Array();
  20521. _this.getScene().addLight(_this);
  20522. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20523. _this._buildUniformLayout();
  20524. _this.includedOnlyMeshes = new Array();
  20525. _this.excludedMeshes = new Array();
  20526. _this._resyncMeshes();
  20527. return _this;
  20528. }
  20529. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20530. /**
  20531. * If every light affecting the material is in this lightmapMode,
  20532. * material.lightmapTexture adds or multiplies
  20533. * (depends on material.useLightmapAsShadowmap)
  20534. * after every other light calculations.
  20535. */
  20536. get: function () {
  20537. return Light._LIGHTMAP_DEFAULT;
  20538. },
  20539. enumerable: true,
  20540. configurable: true
  20541. });
  20542. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20543. /**
  20544. * material.lightmapTexture as only diffuse lighting from this light
  20545. * adds only specular lighting from this light
  20546. * adds dynamic shadows
  20547. */
  20548. get: function () {
  20549. return Light._LIGHTMAP_SPECULAR;
  20550. },
  20551. enumerable: true,
  20552. configurable: true
  20553. });
  20554. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20555. /**
  20556. * material.lightmapTexture as only lighting
  20557. * no light calculation from this light
  20558. * only adds dynamic shadows from this light
  20559. */
  20560. get: function () {
  20561. return Light._LIGHTMAP_SHADOWSONLY;
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20567. /**
  20568. * Each light type uses the default quantity according to its type:
  20569. * point/spot lights use luminous intensity
  20570. * directional lights use illuminance
  20571. */
  20572. get: function () {
  20573. return Light._INTENSITYMODE_AUTOMATIC;
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20579. /**
  20580. * lumen (lm)
  20581. */
  20582. get: function () {
  20583. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20584. },
  20585. enumerable: true,
  20586. configurable: true
  20587. });
  20588. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20589. /**
  20590. * candela (lm/sr)
  20591. */
  20592. get: function () {
  20593. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20594. },
  20595. enumerable: true,
  20596. configurable: true
  20597. });
  20598. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20599. /**
  20600. * lux (lm/m^2)
  20601. */
  20602. get: function () {
  20603. return Light._INTENSITYMODE_ILLUMINANCE;
  20604. },
  20605. enumerable: true,
  20606. configurable: true
  20607. });
  20608. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20609. /**
  20610. * nit (cd/m^2)
  20611. */
  20612. get: function () {
  20613. return Light._INTENSITYMODE_LUMINANCE;
  20614. },
  20615. enumerable: true,
  20616. configurable: true
  20617. });
  20618. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20619. /**
  20620. * Light type const id of the point light.
  20621. */
  20622. get: function () {
  20623. return Light._LIGHTTYPEID_POINTLIGHT;
  20624. },
  20625. enumerable: true,
  20626. configurable: true
  20627. });
  20628. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20629. /**
  20630. * Light type const id of the directional light.
  20631. */
  20632. get: function () {
  20633. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20634. },
  20635. enumerable: true,
  20636. configurable: true
  20637. });
  20638. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20639. /**
  20640. * Light type const id of the spot light.
  20641. */
  20642. get: function () {
  20643. return Light._LIGHTTYPEID_SPOTLIGHT;
  20644. },
  20645. enumerable: true,
  20646. configurable: true
  20647. });
  20648. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20649. /**
  20650. * Light type const id of the hemispheric light.
  20651. */
  20652. get: function () {
  20653. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20654. },
  20655. enumerable: true,
  20656. configurable: true
  20657. });
  20658. Object.defineProperty(Light.prototype, "intensityMode", {
  20659. /**
  20660. * Gets the photometric scale used to interpret the intensity.
  20661. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20662. */
  20663. get: function () {
  20664. return this._intensityMode;
  20665. },
  20666. /**
  20667. * Sets the photometric scale used to interpret the intensity.
  20668. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20669. */
  20670. set: function (value) {
  20671. this._intensityMode = value;
  20672. this._computePhotometricScale();
  20673. },
  20674. enumerable: true,
  20675. configurable: true
  20676. });
  20677. ;
  20678. ;
  20679. Object.defineProperty(Light.prototype, "radius", {
  20680. /**
  20681. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20682. */
  20683. get: function () {
  20684. return this._radius;
  20685. },
  20686. /**
  20687. * sets the light radius used by PBR Materials to simulate soft area lights.
  20688. */
  20689. set: function (value) {
  20690. this._radius = value;
  20691. this._computePhotometricScale();
  20692. },
  20693. enumerable: true,
  20694. configurable: true
  20695. });
  20696. ;
  20697. ;
  20698. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20699. /**
  20700. * Gets the only meshes impacted by this light.
  20701. */
  20702. get: function () {
  20703. return this._includedOnlyMeshes;
  20704. },
  20705. /**
  20706. * Sets the only meshes impacted by this light.
  20707. */
  20708. set: function (value) {
  20709. this._includedOnlyMeshes = value;
  20710. this._hookArrayForIncludedOnly(value);
  20711. },
  20712. enumerable: true,
  20713. configurable: true
  20714. });
  20715. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20716. /**
  20717. * Gets the meshes not impacted by this light.
  20718. */
  20719. get: function () {
  20720. return this._excludedMeshes;
  20721. },
  20722. /**
  20723. * Sets the meshes not impacted by this light.
  20724. */
  20725. set: function (value) {
  20726. this._excludedMeshes = value;
  20727. this._hookArrayForExcluded(value);
  20728. },
  20729. enumerable: true,
  20730. configurable: true
  20731. });
  20732. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  20733. /**
  20734. * Gets the layer id use to find what meshes are not impacted by the light.
  20735. * Inactive if 0
  20736. */
  20737. get: function () {
  20738. return this._excludeWithLayerMask;
  20739. },
  20740. /**
  20741. * Sets the layer id use to find what meshes are not impacted by the light.
  20742. * Inactive if 0
  20743. */
  20744. set: function (value) {
  20745. this._excludeWithLayerMask = value;
  20746. this._resyncMeshes();
  20747. },
  20748. enumerable: true,
  20749. configurable: true
  20750. });
  20751. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  20752. /**
  20753. * Gets the layer id use to find what meshes are impacted by the light.
  20754. * Inactive if 0
  20755. */
  20756. get: function () {
  20757. return this._includeOnlyWithLayerMask;
  20758. },
  20759. /**
  20760. * Sets the layer id use to find what meshes are impacted by the light.
  20761. * Inactive if 0
  20762. */
  20763. set: function (value) {
  20764. this._includeOnlyWithLayerMask = value;
  20765. this._resyncMeshes();
  20766. },
  20767. enumerable: true,
  20768. configurable: true
  20769. });
  20770. Object.defineProperty(Light.prototype, "lightmapMode", {
  20771. /**
  20772. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20773. */
  20774. get: function () {
  20775. return this._lightmapMode;
  20776. },
  20777. /**
  20778. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20779. */
  20780. set: function (value) {
  20781. if (this._lightmapMode === value) {
  20782. return;
  20783. }
  20784. this._lightmapMode = value;
  20785. this._markMeshesAsLightDirty();
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. /**
  20791. * Returns the string "Light".
  20792. * @returns the class name
  20793. */
  20794. Light.prototype.getClassName = function () {
  20795. return "Light";
  20796. };
  20797. /**
  20798. * Converts the light information to a readable string for debug purpose.
  20799. * @param fullDetails Supports for multiple levels of logging within scene loading
  20800. * @returns the human readable light info
  20801. */
  20802. Light.prototype.toString = function (fullDetails) {
  20803. var ret = "Name: " + this.name;
  20804. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  20805. if (this.animations) {
  20806. for (var i = 0; i < this.animations.length; i++) {
  20807. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20808. }
  20809. }
  20810. if (fullDetails) {
  20811. }
  20812. return ret;
  20813. };
  20814. /**
  20815. * Set the enabled state of this node.
  20816. * @param value - the new enabled state
  20817. */
  20818. Light.prototype.setEnabled = function (value) {
  20819. _super.prototype.setEnabled.call(this, value);
  20820. this._resyncMeshes();
  20821. };
  20822. /**
  20823. * Returns the Light associated shadow generator if any.
  20824. * @return the associated shadow generator.
  20825. */
  20826. Light.prototype.getShadowGenerator = function () {
  20827. return this._shadowGenerator;
  20828. };
  20829. /**
  20830. * Returns a Vector3, the absolute light position in the World.
  20831. * @returns the world space position of the light
  20832. */
  20833. Light.prototype.getAbsolutePosition = function () {
  20834. return BABYLON.Vector3.Zero();
  20835. };
  20836. /**
  20837. * Specifies if the light will affect the passed mesh.
  20838. * @param mesh The mesh to test against the light
  20839. * @return true the mesh is affected otherwise, false.
  20840. */
  20841. Light.prototype.canAffectMesh = function (mesh) {
  20842. if (!mesh) {
  20843. return true;
  20844. }
  20845. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  20846. return false;
  20847. }
  20848. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  20849. return false;
  20850. }
  20851. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  20852. return false;
  20853. }
  20854. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  20855. return false;
  20856. }
  20857. return true;
  20858. };
  20859. /**
  20860. * Computes and Returns the light World matrix.
  20861. * @returns the world matrix
  20862. */
  20863. Light.prototype.getWorldMatrix = function () {
  20864. this._currentRenderId = this.getScene().getRenderId();
  20865. this._childRenderId = this._currentRenderId;
  20866. var worldMatrix = this._getWorldMatrix();
  20867. if (this.parent && this.parent.getWorldMatrix) {
  20868. if (!this._parentedWorldMatrix) {
  20869. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  20870. }
  20871. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  20872. this._markSyncedWithParent();
  20873. return this._parentedWorldMatrix;
  20874. }
  20875. return worldMatrix;
  20876. };
  20877. /**
  20878. * Sort function to order lights for rendering.
  20879. * @param a First Light object to compare to second.
  20880. * @param b Second Light object to compare first.
  20881. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  20882. */
  20883. Light.CompareLightsPriority = function (a, b) {
  20884. //shadow-casting lights have priority over non-shadow-casting lights
  20885. //the renderPrioirty is a secondary sort criterion
  20886. if (a.shadowEnabled !== b.shadowEnabled) {
  20887. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  20888. }
  20889. return b.renderPriority - a.renderPriority;
  20890. };
  20891. /**
  20892. * Releases resources associated with this node.
  20893. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20894. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20895. */
  20896. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20897. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20898. if (this._shadowGenerator) {
  20899. this._shadowGenerator.dispose();
  20900. this._shadowGenerator = null;
  20901. }
  20902. // Animations
  20903. this.getScene().stopAnimation(this);
  20904. // Remove from meshes
  20905. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  20906. var mesh = _a[_i];
  20907. mesh._removeLightSource(this);
  20908. }
  20909. this._uniformBuffer.dispose();
  20910. // Remove from scene
  20911. this.getScene().removeLight(this);
  20912. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20913. };
  20914. /**
  20915. * Returns the light type ID (integer).
  20916. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  20917. */
  20918. Light.prototype.getTypeID = function () {
  20919. return 0;
  20920. };
  20921. /**
  20922. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  20923. * @returns the scaled intensity in intensity mode unit
  20924. */
  20925. Light.prototype.getScaledIntensity = function () {
  20926. return this._photometricScale * this.intensity;
  20927. };
  20928. /**
  20929. * Returns a new Light object, named "name", from the current one.
  20930. * @param name The name of the cloned light
  20931. * @returns the new created light
  20932. */
  20933. Light.prototype.clone = function (name) {
  20934. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  20935. if (!constructor) {
  20936. return null;
  20937. }
  20938. return BABYLON.SerializationHelper.Clone(constructor, this);
  20939. };
  20940. /**
  20941. * Serializes the current light into a Serialization object.
  20942. * @returns the serialized object.
  20943. */
  20944. Light.prototype.serialize = function () {
  20945. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20946. // Type
  20947. serializationObject.type = this.getTypeID();
  20948. // Parent
  20949. if (this.parent) {
  20950. serializationObject.parentId = this.parent.id;
  20951. }
  20952. // Inclusion / exclusions
  20953. if (this.excludedMeshes.length > 0) {
  20954. serializationObject.excludedMeshesIds = [];
  20955. this.excludedMeshes.forEach(function (mesh) {
  20956. serializationObject.excludedMeshesIds.push(mesh.id);
  20957. });
  20958. }
  20959. if (this.includedOnlyMeshes.length > 0) {
  20960. serializationObject.includedOnlyMeshesIds = [];
  20961. this.includedOnlyMeshes.forEach(function (mesh) {
  20962. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  20963. });
  20964. }
  20965. // Animations
  20966. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20967. serializationObject.ranges = this.serializeAnimationRanges();
  20968. return serializationObject;
  20969. };
  20970. /**
  20971. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  20972. * This new light is named "name" and added to the passed scene.
  20973. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  20974. * @param name The friendly name of the light
  20975. * @param scene The scene the new light will belong to
  20976. * @returns the constructor function
  20977. */
  20978. Light.GetConstructorFromName = function (type, name, scene) {
  20979. switch (type) {
  20980. case 0:
  20981. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  20982. case 1:
  20983. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  20984. case 2:
  20985. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  20986. case 3:
  20987. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  20988. }
  20989. return null;
  20990. };
  20991. /**
  20992. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  20993. * @param parsedLight The JSON representation of the light
  20994. * @param scene The scene to create the parsed light in
  20995. * @returns the created light after parsing
  20996. */
  20997. Light.Parse = function (parsedLight, scene) {
  20998. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  20999. if (!constructor) {
  21000. return null;
  21001. }
  21002. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21003. // Inclusion / exclusions
  21004. if (parsedLight.excludedMeshesIds) {
  21005. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21006. }
  21007. if (parsedLight.includedOnlyMeshesIds) {
  21008. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21009. }
  21010. // Parent
  21011. if (parsedLight.parentId) {
  21012. light._waitingParentId = parsedLight.parentId;
  21013. }
  21014. // Animations
  21015. if (parsedLight.animations) {
  21016. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21017. var parsedAnimation = parsedLight.animations[animationIndex];
  21018. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21019. }
  21020. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21021. }
  21022. if (parsedLight.autoAnimate) {
  21023. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21024. }
  21025. return light;
  21026. };
  21027. Light.prototype._hookArrayForExcluded = function (array) {
  21028. var _this = this;
  21029. var oldPush = array.push;
  21030. array.push = function () {
  21031. var items = [];
  21032. for (var _i = 0; _i < arguments.length; _i++) {
  21033. items[_i] = arguments[_i];
  21034. }
  21035. var result = oldPush.apply(array, items);
  21036. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21037. var item = items_1[_a];
  21038. item._resyncLighSource(_this);
  21039. }
  21040. return result;
  21041. };
  21042. var oldSplice = array.splice;
  21043. array.splice = function (index, deleteCount) {
  21044. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21045. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21046. var item = deleted_1[_i];
  21047. item._resyncLighSource(_this);
  21048. }
  21049. return deleted;
  21050. };
  21051. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21052. var item = array_1[_i];
  21053. item._resyncLighSource(this);
  21054. }
  21055. };
  21056. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21057. var _this = this;
  21058. var oldPush = array.push;
  21059. array.push = function () {
  21060. var items = [];
  21061. for (var _i = 0; _i < arguments.length; _i++) {
  21062. items[_i] = arguments[_i];
  21063. }
  21064. var result = oldPush.apply(array, items);
  21065. _this._resyncMeshes();
  21066. return result;
  21067. };
  21068. var oldSplice = array.splice;
  21069. array.splice = function (index, deleteCount) {
  21070. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21071. _this._resyncMeshes();
  21072. return deleted;
  21073. };
  21074. this._resyncMeshes();
  21075. };
  21076. Light.prototype._resyncMeshes = function () {
  21077. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21078. var mesh = _a[_i];
  21079. mesh._resyncLighSource(this);
  21080. }
  21081. };
  21082. /**
  21083. * Forces the meshes to update their light related information in their rendering used effects
  21084. * @ignore Internal Use Only
  21085. */
  21086. Light.prototype._markMeshesAsLightDirty = function () {
  21087. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21088. var mesh = _a[_i];
  21089. if (mesh._lightSources.indexOf(this) !== -1) {
  21090. mesh._markSubMeshesAsLightDirty();
  21091. }
  21092. }
  21093. };
  21094. /**
  21095. * Recomputes the cached photometric scale if needed.
  21096. */
  21097. Light.prototype._computePhotometricScale = function () {
  21098. this._photometricScale = this._getPhotometricScale();
  21099. this.getScene().resetCachedMaterial();
  21100. };
  21101. /**
  21102. * Returns the Photometric Scale according to the light type and intensity mode.
  21103. */
  21104. Light.prototype._getPhotometricScale = function () {
  21105. var photometricScale = 0.0;
  21106. var lightTypeID = this.getTypeID();
  21107. //get photometric mode
  21108. var photometricMode = this.intensityMode;
  21109. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21110. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21111. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21112. }
  21113. else {
  21114. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21115. }
  21116. }
  21117. //compute photometric scale
  21118. switch (lightTypeID) {
  21119. case Light.LIGHTTYPEID_POINTLIGHT:
  21120. case Light.LIGHTTYPEID_SPOTLIGHT:
  21121. switch (photometricMode) {
  21122. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21123. photometricScale = 1.0 / (4.0 * Math.PI);
  21124. break;
  21125. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21126. photometricScale = 1.0;
  21127. break;
  21128. case Light.INTENSITYMODE_LUMINANCE:
  21129. photometricScale = this.radius * this.radius;
  21130. break;
  21131. }
  21132. break;
  21133. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21134. switch (photometricMode) {
  21135. case Light.INTENSITYMODE_ILLUMINANCE:
  21136. photometricScale = 1.0;
  21137. break;
  21138. case Light.INTENSITYMODE_LUMINANCE:
  21139. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21140. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21141. var apexAngleRadians = this.radius;
  21142. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21143. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21144. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21145. photometricScale = solidAngle;
  21146. break;
  21147. }
  21148. break;
  21149. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21150. // No fall off in hemisperic light.
  21151. photometricScale = 1.0;
  21152. break;
  21153. }
  21154. return photometricScale;
  21155. };
  21156. /**
  21157. * Reorder the light in the scene according to their defined priority.
  21158. * @ignore Internal Use Only
  21159. */
  21160. Light.prototype._reorderLightsInScene = function () {
  21161. var scene = this.getScene();
  21162. if (this._renderPriority != 0) {
  21163. scene.requireLightSorting = true;
  21164. }
  21165. this.getScene().sortLightsByPriority();
  21166. };
  21167. //lightmapMode Consts
  21168. Light._LIGHTMAP_DEFAULT = 0;
  21169. Light._LIGHTMAP_SPECULAR = 1;
  21170. Light._LIGHTMAP_SHADOWSONLY = 2;
  21171. // Intensity Mode Consts
  21172. Light._INTENSITYMODE_AUTOMATIC = 0;
  21173. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21174. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21175. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21176. Light._INTENSITYMODE_LUMINANCE = 4;
  21177. // Light types ids const.
  21178. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21179. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21180. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21181. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21182. __decorate([
  21183. BABYLON.serializeAsColor3()
  21184. ], Light.prototype, "diffuse", void 0);
  21185. __decorate([
  21186. BABYLON.serializeAsColor3()
  21187. ], Light.prototype, "specular", void 0);
  21188. __decorate([
  21189. BABYLON.serialize()
  21190. ], Light.prototype, "intensity", void 0);
  21191. __decorate([
  21192. BABYLON.serialize()
  21193. ], Light.prototype, "range", void 0);
  21194. __decorate([
  21195. BABYLON.serialize()
  21196. ], Light.prototype, "intensityMode", null);
  21197. __decorate([
  21198. BABYLON.serialize()
  21199. ], Light.prototype, "radius", null);
  21200. __decorate([
  21201. BABYLON.serialize()
  21202. ], Light.prototype, "_renderPriority", void 0);
  21203. __decorate([
  21204. BABYLON.expandToProperty("_reorderLightsInScene")
  21205. ], Light.prototype, "renderPriority", void 0);
  21206. __decorate([
  21207. BABYLON.serialize()
  21208. ], Light.prototype, "shadowEnabled", void 0);
  21209. __decorate([
  21210. BABYLON.serialize("excludeWithLayerMask")
  21211. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21212. __decorate([
  21213. BABYLON.serialize("includeOnlyWithLayerMask")
  21214. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21215. __decorate([
  21216. BABYLON.serialize("lightmapMode")
  21217. ], Light.prototype, "_lightmapMode", void 0);
  21218. return Light;
  21219. }(BABYLON.Node));
  21220. BABYLON.Light = Light;
  21221. })(BABYLON || (BABYLON = {}));
  21222. //# sourceMappingURL=babylon.light.js.map
  21223. "use strict";
  21224. var BABYLON;
  21225. (function (BABYLON) {
  21226. var Camera = /** @class */ (function (_super) {
  21227. __extends(Camera, _super);
  21228. function Camera(name, position, scene) {
  21229. var _this = _super.call(this, name, scene) || this;
  21230. /**
  21231. * The vector the camera should consider as up.
  21232. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21233. */
  21234. _this.upVector = BABYLON.Vector3.Up();
  21235. _this.orthoLeft = null;
  21236. _this.orthoRight = null;
  21237. _this.orthoBottom = null;
  21238. _this.orthoTop = null;
  21239. /**
  21240. * FOV is set in Radians. (default is 0.8)
  21241. */
  21242. _this.fov = 0.8;
  21243. _this.minZ = 1;
  21244. _this.maxZ = 10000.0;
  21245. _this.inertia = 0.9;
  21246. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21247. _this.isIntermediate = false;
  21248. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21249. /**
  21250. * Restricts the camera to viewing objects with the same layerMask.
  21251. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21252. */
  21253. _this.layerMask = 0x0FFFFFFF;
  21254. /**
  21255. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21256. */
  21257. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21258. // Camera rig members
  21259. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21260. _this._rigCameras = new Array();
  21261. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21262. _this._skipRendering = false;
  21263. _this.customRenderTargets = new Array();
  21264. // Observables
  21265. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21266. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21267. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21268. _this.onRestoreStateObservable = new BABYLON.Observable();
  21269. // Cache
  21270. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21271. _this._projectionMatrix = new BABYLON.Matrix();
  21272. _this._doNotComputeProjectionMatrix = false;
  21273. _this._postProcesses = new Array();
  21274. _this._transformMatrix = BABYLON.Matrix.Zero();
  21275. _this._activeMeshes = new BABYLON.SmartArray(256);
  21276. _this._globalPosition = BABYLON.Vector3.Zero();
  21277. _this._refreshFrustumPlanes = true;
  21278. _this.getScene().addCamera(_this);
  21279. if (!_this.getScene().activeCamera) {
  21280. _this.getScene().activeCamera = _this;
  21281. }
  21282. _this.position = position;
  21283. return _this;
  21284. }
  21285. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21286. get: function () {
  21287. return Camera._PERSPECTIVE_CAMERA;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21293. get: function () {
  21294. return Camera._ORTHOGRAPHIC_CAMERA;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21300. /**
  21301. * This is the default FOV mode for perspective cameras.
  21302. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21303. *
  21304. */
  21305. get: function () {
  21306. return Camera._FOVMODE_VERTICAL_FIXED;
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21312. /**
  21313. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21314. *
  21315. */
  21316. get: function () {
  21317. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21318. },
  21319. enumerable: true,
  21320. configurable: true
  21321. });
  21322. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21323. get: function () {
  21324. return Camera._RIG_MODE_NONE;
  21325. },
  21326. enumerable: true,
  21327. configurable: true
  21328. });
  21329. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21330. get: function () {
  21331. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21332. },
  21333. enumerable: true,
  21334. configurable: true
  21335. });
  21336. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21337. get: function () {
  21338. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21344. get: function () {
  21345. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21346. },
  21347. enumerable: true,
  21348. configurable: true
  21349. });
  21350. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21351. get: function () {
  21352. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21353. },
  21354. enumerable: true,
  21355. configurable: true
  21356. });
  21357. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21358. get: function () {
  21359. return Camera._RIG_MODE_VR;
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21365. get: function () {
  21366. return Camera._RIG_MODE_WEBVR;
  21367. },
  21368. enumerable: true,
  21369. configurable: true
  21370. });
  21371. /**
  21372. * Store current camera state (fov, position, etc..)
  21373. */
  21374. Camera.prototype.storeState = function () {
  21375. this._stateStored = true;
  21376. this._storedFov = this.fov;
  21377. return this;
  21378. };
  21379. /**
  21380. * Restores the camera state values if it has been stored. You must call storeState() first
  21381. */
  21382. Camera.prototype._restoreStateValues = function () {
  21383. if (!this._stateStored) {
  21384. return false;
  21385. }
  21386. this.fov = this._storedFov;
  21387. return true;
  21388. };
  21389. /**
  21390. * Restored camera state. You must call storeState() first
  21391. */
  21392. Camera.prototype.restoreState = function () {
  21393. if (this._restoreStateValues()) {
  21394. this.onRestoreStateObservable.notifyObservers(this);
  21395. return true;
  21396. }
  21397. return false;
  21398. };
  21399. Camera.prototype.getClassName = function () {
  21400. return "Camera";
  21401. };
  21402. /**
  21403. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21404. */
  21405. Camera.prototype.toString = function (fullDetails) {
  21406. var ret = "Name: " + this.name;
  21407. ret += ", type: " + this.getClassName();
  21408. if (this.animations) {
  21409. for (var i = 0; i < this.animations.length; i++) {
  21410. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21411. }
  21412. }
  21413. if (fullDetails) {
  21414. }
  21415. return ret;
  21416. };
  21417. Object.defineProperty(Camera.prototype, "globalPosition", {
  21418. get: function () {
  21419. return this._globalPosition;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. Camera.prototype.getActiveMeshes = function () {
  21425. return this._activeMeshes;
  21426. };
  21427. Camera.prototype.isActiveMesh = function (mesh) {
  21428. return (this._activeMeshes.indexOf(mesh) !== -1);
  21429. };
  21430. /**
  21431. * Is this camera ready to be used/rendered
  21432. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21433. * @return true if the camera is ready
  21434. */
  21435. Camera.prototype.isReady = function (completeCheck) {
  21436. if (completeCheck === void 0) { completeCheck = false; }
  21437. if (completeCheck) {
  21438. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21439. var pp = _a[_i];
  21440. if (pp && !pp.isReady()) {
  21441. return false;
  21442. }
  21443. }
  21444. }
  21445. return _super.prototype.isReady.call(this, completeCheck);
  21446. };
  21447. //Cache
  21448. Camera.prototype._initCache = function () {
  21449. _super.prototype._initCache.call(this);
  21450. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21451. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21452. this._cache.mode = undefined;
  21453. this._cache.minZ = undefined;
  21454. this._cache.maxZ = undefined;
  21455. this._cache.fov = undefined;
  21456. this._cache.fovMode = undefined;
  21457. this._cache.aspectRatio = undefined;
  21458. this._cache.orthoLeft = undefined;
  21459. this._cache.orthoRight = undefined;
  21460. this._cache.orthoBottom = undefined;
  21461. this._cache.orthoTop = undefined;
  21462. this._cache.renderWidth = undefined;
  21463. this._cache.renderHeight = undefined;
  21464. };
  21465. Camera.prototype._updateCache = function (ignoreParentClass) {
  21466. if (!ignoreParentClass) {
  21467. _super.prototype._updateCache.call(this);
  21468. }
  21469. this._cache.position.copyFrom(this.position);
  21470. this._cache.upVector.copyFrom(this.upVector);
  21471. };
  21472. // Synchronized
  21473. Camera.prototype._isSynchronized = function () {
  21474. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21475. };
  21476. Camera.prototype._isSynchronizedViewMatrix = function () {
  21477. if (!_super.prototype._isSynchronized.call(this))
  21478. return false;
  21479. return this._cache.position.equals(this.position)
  21480. && this._cache.upVector.equals(this.upVector)
  21481. && this.isSynchronizedWithParent();
  21482. };
  21483. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21484. var check = this._cache.mode === this.mode
  21485. && this._cache.minZ === this.minZ
  21486. && this._cache.maxZ === this.maxZ;
  21487. if (!check) {
  21488. return false;
  21489. }
  21490. var engine = this.getEngine();
  21491. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21492. check = this._cache.fov === this.fov
  21493. && this._cache.fovMode === this.fovMode
  21494. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21495. }
  21496. else {
  21497. check = this._cache.orthoLeft === this.orthoLeft
  21498. && this._cache.orthoRight === this.orthoRight
  21499. && this._cache.orthoBottom === this.orthoBottom
  21500. && this._cache.orthoTop === this.orthoTop
  21501. && this._cache.renderWidth === engine.getRenderWidth()
  21502. && this._cache.renderHeight === engine.getRenderHeight();
  21503. }
  21504. return check;
  21505. };
  21506. // Controls
  21507. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21508. };
  21509. Camera.prototype.detachControl = function (element) {
  21510. };
  21511. Camera.prototype.update = function () {
  21512. this._checkInputs();
  21513. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21514. this._updateRigCameras();
  21515. }
  21516. };
  21517. Camera.prototype._checkInputs = function () {
  21518. this.onAfterCheckInputsObservable.notifyObservers(this);
  21519. };
  21520. Object.defineProperty(Camera.prototype, "rigCameras", {
  21521. get: function () {
  21522. return this._rigCameras;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21528. get: function () {
  21529. return this._rigPostProcess;
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. /**
  21535. * Internal, gets the first post proces.
  21536. * @returns the first post process to be run on this camera.
  21537. */
  21538. Camera.prototype._getFirstPostProcess = function () {
  21539. for (var pp in this._postProcesses) {
  21540. if (this._postProcesses[pp] !== null) {
  21541. return this._postProcesses[pp];
  21542. }
  21543. }
  21544. return null;
  21545. };
  21546. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21547. // invalidate framebuffer
  21548. var firstPostProcess = this._getFirstPostProcess();
  21549. if (firstPostProcess) {
  21550. firstPostProcess.markTextureDirty();
  21551. }
  21552. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21553. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21554. var cam = this._rigCameras[i];
  21555. var rigPostProcess = cam._rigPostProcess;
  21556. // for VR rig, there does not have to be a post process
  21557. if (rigPostProcess) {
  21558. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21559. if (isPass) {
  21560. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21561. cam.isIntermediate = this._postProcesses.length === 0;
  21562. }
  21563. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21564. rigPostProcess.markTextureDirty();
  21565. }
  21566. else {
  21567. cam._postProcesses = this._postProcesses.slice(0);
  21568. }
  21569. }
  21570. };
  21571. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21572. if (insertAt === void 0) { insertAt = null; }
  21573. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21574. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21575. return 0;
  21576. }
  21577. if (insertAt == null || insertAt < 0) {
  21578. this._postProcesses.push(postProcess);
  21579. }
  21580. else if (this._postProcesses[insertAt] === null) {
  21581. this._postProcesses[insertAt] = postProcess;
  21582. }
  21583. else {
  21584. this._postProcesses.splice(insertAt, 0, postProcess);
  21585. }
  21586. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21587. return this._postProcesses.indexOf(postProcess);
  21588. };
  21589. Camera.prototype.detachPostProcess = function (postProcess) {
  21590. var idx = this._postProcesses.indexOf(postProcess);
  21591. if (idx !== -1) {
  21592. this._postProcesses[idx] = null;
  21593. }
  21594. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21595. };
  21596. Camera.prototype.getWorldMatrix = function () {
  21597. if (!this._worldMatrix) {
  21598. this._worldMatrix = BABYLON.Matrix.Identity();
  21599. }
  21600. var viewMatrix = this.getViewMatrix();
  21601. viewMatrix.invertToRef(this._worldMatrix);
  21602. return this._worldMatrix;
  21603. };
  21604. Camera.prototype._getViewMatrix = function () {
  21605. return BABYLON.Matrix.Identity();
  21606. };
  21607. Camera.prototype.getViewMatrix = function (force) {
  21608. if (!force && this._isSynchronizedViewMatrix()) {
  21609. return this._computedViewMatrix;
  21610. }
  21611. this.updateCache();
  21612. this._computedViewMatrix = this._getViewMatrix();
  21613. this._currentRenderId = this.getScene().getRenderId();
  21614. this._childRenderId = this._currentRenderId;
  21615. this._refreshFrustumPlanes = true;
  21616. if (!this.parent || !this.parent.getWorldMatrix) {
  21617. this._globalPosition.copyFrom(this.position);
  21618. }
  21619. else {
  21620. if (!this._worldMatrix) {
  21621. this._worldMatrix = BABYLON.Matrix.Identity();
  21622. }
  21623. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21624. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21625. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21626. this._computedViewMatrix.invert();
  21627. this._markSyncedWithParent();
  21628. }
  21629. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21630. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21631. }
  21632. this.onViewMatrixChangedObservable.notifyObservers(this);
  21633. return this._computedViewMatrix;
  21634. };
  21635. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21636. this._doNotComputeProjectionMatrix = true;
  21637. if (projection !== undefined) {
  21638. this._projectionMatrix = projection;
  21639. }
  21640. };
  21641. ;
  21642. Camera.prototype.unfreezeProjectionMatrix = function () {
  21643. this._doNotComputeProjectionMatrix = false;
  21644. };
  21645. ;
  21646. Camera.prototype.getProjectionMatrix = function (force) {
  21647. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21648. return this._projectionMatrix;
  21649. }
  21650. // Cache
  21651. this._cache.mode = this.mode;
  21652. this._cache.minZ = this.minZ;
  21653. this._cache.maxZ = this.maxZ;
  21654. // Matrix
  21655. this._refreshFrustumPlanes = true;
  21656. var engine = this.getEngine();
  21657. var scene = this.getScene();
  21658. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21659. this._cache.fov = this.fov;
  21660. this._cache.fovMode = this.fovMode;
  21661. this._cache.aspectRatio = engine.getAspectRatio(this);
  21662. if (this.minZ <= 0) {
  21663. this.minZ = 0.1;
  21664. }
  21665. if (scene.useRightHandedSystem) {
  21666. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21667. }
  21668. else {
  21669. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21670. }
  21671. }
  21672. else {
  21673. var halfWidth = engine.getRenderWidth() / 2.0;
  21674. var halfHeight = engine.getRenderHeight() / 2.0;
  21675. if (scene.useRightHandedSystem) {
  21676. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21677. }
  21678. else {
  21679. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21680. }
  21681. this._cache.orthoLeft = this.orthoLeft;
  21682. this._cache.orthoRight = this.orthoRight;
  21683. this._cache.orthoBottom = this.orthoBottom;
  21684. this._cache.orthoTop = this.orthoTop;
  21685. this._cache.renderWidth = engine.getRenderWidth();
  21686. this._cache.renderHeight = engine.getRenderHeight();
  21687. }
  21688. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21689. return this._projectionMatrix;
  21690. };
  21691. Camera.prototype.getTranformationMatrix = function () {
  21692. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21693. return this._transformMatrix;
  21694. };
  21695. Camera.prototype.updateFrustumPlanes = function () {
  21696. if (!this._refreshFrustumPlanes) {
  21697. return;
  21698. }
  21699. this.getTranformationMatrix();
  21700. if (!this._frustumPlanes) {
  21701. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21702. }
  21703. else {
  21704. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21705. }
  21706. this._refreshFrustumPlanes = false;
  21707. };
  21708. Camera.prototype.isInFrustum = function (target) {
  21709. this.updateFrustumPlanes();
  21710. return target.isInFrustum(this._frustumPlanes);
  21711. };
  21712. Camera.prototype.isCompletelyInFrustum = function (target) {
  21713. this.updateFrustumPlanes();
  21714. return target.isCompletelyInFrustum(this._frustumPlanes);
  21715. };
  21716. Camera.prototype.getForwardRay = function (length, transform, origin) {
  21717. if (length === void 0) { length = 100; }
  21718. if (!transform) {
  21719. transform = this.getWorldMatrix();
  21720. }
  21721. if (!origin) {
  21722. origin = this.position;
  21723. }
  21724. var forward = new BABYLON.Vector3(0, 0, 1);
  21725. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  21726. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  21727. return new BABYLON.Ray(origin, direction, length);
  21728. };
  21729. /**
  21730. * Releases resources associated with this node.
  21731. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21732. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21733. */
  21734. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21735. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21736. // Observables
  21737. this.onViewMatrixChangedObservable.clear();
  21738. this.onProjectionMatrixChangedObservable.clear();
  21739. this.onAfterCheckInputsObservable.clear();
  21740. this.onRestoreStateObservable.clear();
  21741. // Inputs
  21742. if (this.inputs) {
  21743. this.inputs.clear();
  21744. }
  21745. // Animations
  21746. this.getScene().stopAnimation(this);
  21747. // Remove from scene
  21748. this.getScene().removeCamera(this);
  21749. while (this._rigCameras.length > 0) {
  21750. var camera = this._rigCameras.pop();
  21751. if (camera) {
  21752. camera.dispose();
  21753. }
  21754. }
  21755. // Postprocesses
  21756. if (this._rigPostProcess) {
  21757. this._rigPostProcess.dispose(this);
  21758. this._rigPostProcess = null;
  21759. this._postProcesses = [];
  21760. }
  21761. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21762. this._rigPostProcess = null;
  21763. this._postProcesses = [];
  21764. }
  21765. else {
  21766. var i = this._postProcesses.length;
  21767. while (--i >= 0) {
  21768. var postProcess = this._postProcesses[i];
  21769. if (postProcess) {
  21770. postProcess.dispose(this);
  21771. }
  21772. }
  21773. }
  21774. // Render targets
  21775. var i = this.customRenderTargets.length;
  21776. while (--i >= 0) {
  21777. this.customRenderTargets[i].dispose();
  21778. }
  21779. this.customRenderTargets = [];
  21780. // Active Meshes
  21781. this._activeMeshes.dispose();
  21782. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21783. };
  21784. Object.defineProperty(Camera.prototype, "leftCamera", {
  21785. // ---- Camera rigs section ----
  21786. get: function () {
  21787. if (this._rigCameras.length < 1) {
  21788. return null;
  21789. }
  21790. return this._rigCameras[0];
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(Camera.prototype, "rightCamera", {
  21796. get: function () {
  21797. if (this._rigCameras.length < 2) {
  21798. return null;
  21799. }
  21800. return this._rigCameras[1];
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Camera.prototype.getLeftTarget = function () {
  21806. if (this._rigCameras.length < 1) {
  21807. return null;
  21808. }
  21809. return this._rigCameras[0].getTarget();
  21810. };
  21811. Camera.prototype.getRightTarget = function () {
  21812. if (this._rigCameras.length < 2) {
  21813. return null;
  21814. }
  21815. return this._rigCameras[1].getTarget();
  21816. };
  21817. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  21818. if (this.cameraRigMode === mode) {
  21819. return;
  21820. }
  21821. while (this._rigCameras.length > 0) {
  21822. var camera = this._rigCameras.pop();
  21823. if (camera) {
  21824. camera.dispose();
  21825. }
  21826. }
  21827. this.cameraRigMode = mode;
  21828. this._cameraRigParams = {};
  21829. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  21830. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  21831. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  21832. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  21833. // create the rig cameras, unless none
  21834. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21835. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  21836. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  21837. if (leftCamera && rightCamera) {
  21838. this._rigCameras.push(leftCamera);
  21839. this._rigCameras.push(rightCamera);
  21840. }
  21841. }
  21842. switch (this.cameraRigMode) {
  21843. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  21844. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  21845. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  21846. break;
  21847. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  21848. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  21849. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  21850. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21851. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  21852. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  21853. break;
  21854. case Camera.RIG_MODE_VR:
  21855. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  21856. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  21857. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  21858. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21859. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  21860. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  21861. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  21862. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  21863. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  21864. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21865. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  21866. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  21867. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  21868. if (metrics.compensateDistortion) {
  21869. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  21870. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  21871. }
  21872. break;
  21873. case Camera.RIG_MODE_WEBVR:
  21874. if (rigParams.vrDisplay) {
  21875. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  21876. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  21877. //Left eye
  21878. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  21879. this._rigCameras[0].setCameraRigParameter("left", true);
  21880. //leaving this for future reference
  21881. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  21882. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  21883. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  21884. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  21885. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21886. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  21887. this._rigCameras[0].parent = this;
  21888. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  21889. //Right eye
  21890. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  21891. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  21892. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  21893. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  21894. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  21895. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21896. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  21897. this._rigCameras[1].parent = this;
  21898. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  21899. if (Camera.UseAlternateWebVRRendering) {
  21900. this._rigCameras[1]._skipRendering = true;
  21901. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  21902. }
  21903. }
  21904. break;
  21905. }
  21906. this._cascadePostProcessesToRigCams();
  21907. this.update();
  21908. };
  21909. Camera.prototype._getVRProjectionMatrix = function () {
  21910. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  21911. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  21912. return this._projectionMatrix;
  21913. };
  21914. Camera.prototype._updateCameraRotationMatrix = function () {
  21915. //Here for WebVR
  21916. };
  21917. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  21918. //Here for WebVR
  21919. };
  21920. /**
  21921. * This function MUST be overwritten by the different WebVR cameras available.
  21922. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  21923. */
  21924. Camera.prototype._getWebVRProjectionMatrix = function () {
  21925. return BABYLON.Matrix.Identity();
  21926. };
  21927. /**
  21928. * This function MUST be overwritten by the different WebVR cameras available.
  21929. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  21930. */
  21931. Camera.prototype._getWebVRViewMatrix = function () {
  21932. return BABYLON.Matrix.Identity();
  21933. };
  21934. Camera.prototype.setCameraRigParameter = function (name, value) {
  21935. if (!this._cameraRigParams) {
  21936. this._cameraRigParams = {};
  21937. }
  21938. this._cameraRigParams[name] = value;
  21939. //provisionnally:
  21940. if (name === "interaxialDistance") {
  21941. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  21942. }
  21943. };
  21944. /**
  21945. * needs to be overridden by children so sub has required properties to be copied
  21946. */
  21947. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  21948. return null;
  21949. };
  21950. /**
  21951. * May need to be overridden by children
  21952. */
  21953. Camera.prototype._updateRigCameras = function () {
  21954. for (var i = 0; i < this._rigCameras.length; i++) {
  21955. this._rigCameras[i].minZ = this.minZ;
  21956. this._rigCameras[i].maxZ = this.maxZ;
  21957. this._rigCameras[i].fov = this.fov;
  21958. }
  21959. // only update viewport when ANAGLYPH
  21960. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  21961. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  21962. }
  21963. };
  21964. Camera.prototype._setupInputs = function () {
  21965. };
  21966. Camera.prototype.serialize = function () {
  21967. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21968. // Type
  21969. serializationObject.type = this.getClassName();
  21970. // Parent
  21971. if (this.parent) {
  21972. serializationObject.parentId = this.parent.id;
  21973. }
  21974. if (this.inputs) {
  21975. this.inputs.serialize(serializationObject);
  21976. }
  21977. // Animations
  21978. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21979. serializationObject.ranges = this.serializeAnimationRanges();
  21980. return serializationObject;
  21981. };
  21982. Camera.prototype.clone = function (name) {
  21983. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  21984. };
  21985. Camera.prototype.getDirection = function (localAxis) {
  21986. var result = BABYLON.Vector3.Zero();
  21987. this.getDirectionToRef(localAxis, result);
  21988. return result;
  21989. };
  21990. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  21991. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  21992. };
  21993. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  21994. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  21995. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  21996. switch (type) {
  21997. case "ArcRotateCamera":
  21998. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  21999. case "DeviceOrientationCamera":
  22000. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22001. case "FollowCamera":
  22002. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22003. case "ArcFollowCamera":
  22004. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22005. case "GamepadCamera":
  22006. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22007. case "TouchCamera":
  22008. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22009. case "VirtualJoysticksCamera":
  22010. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22011. case "WebVRFreeCamera":
  22012. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22013. case "WebVRGamepadCamera":
  22014. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22015. case "VRDeviceOrientationFreeCamera":
  22016. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22017. case "VRDeviceOrientationGamepadCamera":
  22018. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22019. case "AnaglyphArcRotateCamera":
  22020. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22021. case "AnaglyphFreeCamera":
  22022. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22023. case "AnaglyphGamepadCamera":
  22024. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22025. case "AnaglyphUniversalCamera":
  22026. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22027. case "StereoscopicArcRotateCamera":
  22028. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22029. case "StereoscopicFreeCamera":
  22030. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22031. case "StereoscopicGamepadCamera":
  22032. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22033. case "StereoscopicUniversalCamera":
  22034. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22035. case "FreeCamera":// Forcing Universal here
  22036. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22037. default:// Universal Camera is the default value
  22038. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22039. }
  22040. };
  22041. Camera.prototype.computeWorldMatrix = function () {
  22042. return this.getWorldMatrix();
  22043. };
  22044. Camera.Parse = function (parsedCamera, scene) {
  22045. var type = parsedCamera.type;
  22046. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22047. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22048. // Parent
  22049. if (parsedCamera.parentId) {
  22050. camera._waitingParentId = parsedCamera.parentId;
  22051. }
  22052. //If camera has an input manager, let it parse inputs settings
  22053. if (camera.inputs) {
  22054. camera.inputs.parse(parsedCamera);
  22055. camera._setupInputs();
  22056. }
  22057. if (camera.setPosition) {
  22058. camera.position.copyFromFloats(0, 0, 0);
  22059. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22060. }
  22061. // Target
  22062. if (parsedCamera.target) {
  22063. if (camera.setTarget) {
  22064. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22065. }
  22066. }
  22067. // Apply 3d rig, when found
  22068. if (parsedCamera.cameraRigMode) {
  22069. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22070. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22071. }
  22072. // Animations
  22073. if (parsedCamera.animations) {
  22074. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22075. var parsedAnimation = parsedCamera.animations[animationIndex];
  22076. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22077. }
  22078. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22079. }
  22080. if (parsedCamera.autoAnimate) {
  22081. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22082. }
  22083. return camera;
  22084. };
  22085. // Statics
  22086. Camera._PERSPECTIVE_CAMERA = 0;
  22087. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22088. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22089. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22090. Camera._RIG_MODE_NONE = 0;
  22091. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22092. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22093. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22094. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22095. Camera._RIG_MODE_VR = 20;
  22096. Camera._RIG_MODE_WEBVR = 21;
  22097. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22098. Camera.UseAlternateWebVRRendering = false;
  22099. __decorate([
  22100. BABYLON.serializeAsVector3()
  22101. ], Camera.prototype, "position", void 0);
  22102. __decorate([
  22103. BABYLON.serializeAsVector3()
  22104. ], Camera.prototype, "upVector", void 0);
  22105. __decorate([
  22106. BABYLON.serialize()
  22107. ], Camera.prototype, "orthoLeft", void 0);
  22108. __decorate([
  22109. BABYLON.serialize()
  22110. ], Camera.prototype, "orthoRight", void 0);
  22111. __decorate([
  22112. BABYLON.serialize()
  22113. ], Camera.prototype, "orthoBottom", void 0);
  22114. __decorate([
  22115. BABYLON.serialize()
  22116. ], Camera.prototype, "orthoTop", void 0);
  22117. __decorate([
  22118. BABYLON.serialize()
  22119. ], Camera.prototype, "fov", void 0);
  22120. __decorate([
  22121. BABYLON.serialize()
  22122. ], Camera.prototype, "minZ", void 0);
  22123. __decorate([
  22124. BABYLON.serialize()
  22125. ], Camera.prototype, "maxZ", void 0);
  22126. __decorate([
  22127. BABYLON.serialize()
  22128. ], Camera.prototype, "inertia", void 0);
  22129. __decorate([
  22130. BABYLON.serialize()
  22131. ], Camera.prototype, "mode", void 0);
  22132. __decorate([
  22133. BABYLON.serialize()
  22134. ], Camera.prototype, "layerMask", void 0);
  22135. __decorate([
  22136. BABYLON.serialize()
  22137. ], Camera.prototype, "fovMode", void 0);
  22138. __decorate([
  22139. BABYLON.serialize()
  22140. ], Camera.prototype, "cameraRigMode", void 0);
  22141. __decorate([
  22142. BABYLON.serialize()
  22143. ], Camera.prototype, "interaxialDistance", void 0);
  22144. __decorate([
  22145. BABYLON.serialize()
  22146. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22147. return Camera;
  22148. }(BABYLON.Node));
  22149. BABYLON.Camera = Camera;
  22150. })(BABYLON || (BABYLON = {}));
  22151. //# sourceMappingURL=babylon.camera.js.map
  22152. "use strict";
  22153. var BABYLON;
  22154. (function (BABYLON) {
  22155. var RenderingManager = /** @class */ (function () {
  22156. function RenderingManager(scene) {
  22157. this._renderingGroups = new Array();
  22158. this._autoClearDepthStencil = {};
  22159. this._customOpaqueSortCompareFn = {};
  22160. this._customAlphaTestSortCompareFn = {};
  22161. this._customTransparentSortCompareFn = {};
  22162. this._renderinGroupInfo = null;
  22163. this._scene = scene;
  22164. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22165. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22166. }
  22167. }
  22168. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22169. if (depth === void 0) { depth = true; }
  22170. if (stencil === void 0) { stencil = true; }
  22171. if (this._depthStencilBufferAlreadyCleaned) {
  22172. return;
  22173. }
  22174. this._scene.getEngine().clear(null, false, depth, stencil);
  22175. this._depthStencilBufferAlreadyCleaned = true;
  22176. };
  22177. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22178. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22179. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22180. var info = null;
  22181. if (observable) {
  22182. if (!this._renderinGroupInfo) {
  22183. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22184. }
  22185. info = this._renderinGroupInfo;
  22186. info.scene = this._scene;
  22187. info.camera = this._scene.activeCamera;
  22188. }
  22189. // Dispatch sprites
  22190. if (renderSprites) {
  22191. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22192. var manager = this._scene.spriteManagers[index];
  22193. this.dispatchSprites(manager);
  22194. }
  22195. }
  22196. // Render
  22197. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22198. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22199. var renderingGroup = this._renderingGroups[index];
  22200. if (!renderingGroup && !observable)
  22201. continue;
  22202. var renderingGroupMask = 0;
  22203. // Fire PRECLEAR stage
  22204. if (observable && info) {
  22205. renderingGroupMask = Math.pow(2, index);
  22206. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22207. info.renderingGroupId = index;
  22208. observable.notifyObservers(info, renderingGroupMask);
  22209. }
  22210. // Clear depth/stencil if needed
  22211. if (RenderingManager.AUTOCLEAR) {
  22212. var autoClear = this._autoClearDepthStencil[index];
  22213. if (autoClear && autoClear.autoClear) {
  22214. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22215. }
  22216. }
  22217. if (observable && info) {
  22218. // Fire PREOPAQUE stage
  22219. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22220. observable.notifyObservers(info, renderingGroupMask);
  22221. // Fire PRETRANSPARENT stage
  22222. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22223. observable.notifyObservers(info, renderingGroupMask);
  22224. }
  22225. if (renderingGroup)
  22226. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22227. // Fire POSTTRANSPARENT stage
  22228. if (observable && info) {
  22229. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22230. observable.notifyObservers(info, renderingGroupMask);
  22231. }
  22232. }
  22233. };
  22234. RenderingManager.prototype.reset = function () {
  22235. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22236. var renderingGroup = this._renderingGroups[index];
  22237. if (renderingGroup) {
  22238. renderingGroup.prepare();
  22239. }
  22240. }
  22241. };
  22242. RenderingManager.prototype.dispose = function () {
  22243. this.freeRenderingGroups();
  22244. this._renderingGroups.length = 0;
  22245. };
  22246. /**
  22247. * Clear the info related to rendering groups preventing retention points during dispose.
  22248. */
  22249. RenderingManager.prototype.freeRenderingGroups = function () {
  22250. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22251. var renderingGroup = this._renderingGroups[index];
  22252. if (renderingGroup) {
  22253. renderingGroup.dispose();
  22254. }
  22255. }
  22256. };
  22257. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22258. if (this._renderingGroups[renderingGroupId] === undefined) {
  22259. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22260. }
  22261. };
  22262. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22263. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22264. this._prepareRenderingGroup(renderingGroupId);
  22265. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22266. };
  22267. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22268. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22269. this._prepareRenderingGroup(renderingGroupId);
  22270. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22271. };
  22272. /**
  22273. * @param subMesh The submesh to dispatch
  22274. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22275. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22276. */
  22277. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22278. if (mesh === undefined) {
  22279. mesh = subMesh.getMesh();
  22280. }
  22281. var renderingGroupId = mesh.renderingGroupId || 0;
  22282. this._prepareRenderingGroup(renderingGroupId);
  22283. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22284. };
  22285. /**
  22286. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22287. * This allowed control for front to back rendering or reversly depending of the special needs.
  22288. *
  22289. * @param renderingGroupId The rendering group id corresponding to its index
  22290. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22291. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22292. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22293. */
  22294. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22295. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22296. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22297. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22298. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22299. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22300. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22301. if (this._renderingGroups[renderingGroupId]) {
  22302. var group = this._renderingGroups[renderingGroupId];
  22303. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22304. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22305. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22306. }
  22307. };
  22308. /**
  22309. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22310. *
  22311. * @param renderingGroupId The rendering group id corresponding to its index
  22312. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22313. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22314. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22315. */
  22316. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22317. if (depth === void 0) { depth = true; }
  22318. if (stencil === void 0) { stencil = true; }
  22319. this._autoClearDepthStencil[renderingGroupId] = {
  22320. autoClear: autoClearDepthStencil,
  22321. depth: depth,
  22322. stencil: stencil
  22323. };
  22324. };
  22325. /**
  22326. * The max id used for rendering groups (not included)
  22327. */
  22328. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22329. /**
  22330. * The min id used for rendering groups (included)
  22331. */
  22332. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22333. /**
  22334. * Used to globally prevent autoclearing scenes.
  22335. */
  22336. RenderingManager.AUTOCLEAR = true;
  22337. return RenderingManager;
  22338. }());
  22339. BABYLON.RenderingManager = RenderingManager;
  22340. })(BABYLON || (BABYLON = {}));
  22341. //# sourceMappingURL=babylon.renderingManager.js.map
  22342. "use strict";
  22343. var BABYLON;
  22344. (function (BABYLON) {
  22345. var RenderingGroup = /** @class */ (function () {
  22346. /**
  22347. * Creates a new rendering group.
  22348. * @param index The rendering group index
  22349. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22350. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22351. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22352. */
  22353. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22354. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22355. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22356. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22357. this.index = index;
  22358. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22359. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22360. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22361. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22362. this._particleSystems = new BABYLON.SmartArray(256);
  22363. this._spriteManagers = new BABYLON.SmartArray(256);
  22364. this._edgesRenderers = new BABYLON.SmartArray(16);
  22365. this._scene = scene;
  22366. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22367. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22368. this.transparentSortCompareFn = transparentSortCompareFn;
  22369. }
  22370. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22371. /**
  22372. * Set the opaque sort comparison function.
  22373. * If null the sub meshes will be render in the order they were created
  22374. */
  22375. set: function (value) {
  22376. this._opaqueSortCompareFn = value;
  22377. if (value) {
  22378. this._renderOpaque = this.renderOpaqueSorted;
  22379. }
  22380. else {
  22381. this._renderOpaque = RenderingGroup.renderUnsorted;
  22382. }
  22383. },
  22384. enumerable: true,
  22385. configurable: true
  22386. });
  22387. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22388. /**
  22389. * Set the alpha test sort comparison function.
  22390. * If null the sub meshes will be render in the order they were created
  22391. */
  22392. set: function (value) {
  22393. this._alphaTestSortCompareFn = value;
  22394. if (value) {
  22395. this._renderAlphaTest = this.renderAlphaTestSorted;
  22396. }
  22397. else {
  22398. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22399. }
  22400. },
  22401. enumerable: true,
  22402. configurable: true
  22403. });
  22404. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22405. /**
  22406. * Set the transparent sort comparison function.
  22407. * If null the sub meshes will be render in the order they were created
  22408. */
  22409. set: function (value) {
  22410. if (value) {
  22411. this._transparentSortCompareFn = value;
  22412. }
  22413. else {
  22414. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22415. }
  22416. this._renderTransparent = this.renderTransparentSorted;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. /**
  22422. * Render all the sub meshes contained in the group.
  22423. * @param customRenderFunction Used to override the default render behaviour of the group.
  22424. * @returns true if rendered some submeshes.
  22425. */
  22426. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22427. if (customRenderFunction) {
  22428. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22429. return;
  22430. }
  22431. var engine = this._scene.getEngine();
  22432. // Depth only
  22433. if (this._depthOnlySubMeshes.length !== 0) {
  22434. engine.setColorWrite(false);
  22435. this._renderAlphaTest(this._depthOnlySubMeshes);
  22436. engine.setColorWrite(true);
  22437. }
  22438. // Opaque
  22439. if (this._opaqueSubMeshes.length !== 0) {
  22440. this._renderOpaque(this._opaqueSubMeshes);
  22441. }
  22442. // Alpha test
  22443. if (this._alphaTestSubMeshes.length !== 0) {
  22444. this._renderAlphaTest(this._alphaTestSubMeshes);
  22445. }
  22446. var stencilState = engine.getStencilBuffer();
  22447. engine.setStencilBuffer(false);
  22448. // Sprites
  22449. if (renderSprites) {
  22450. this._renderSprites();
  22451. }
  22452. // Particles
  22453. if (renderParticles) {
  22454. this._renderParticles(activeMeshes);
  22455. }
  22456. if (this.onBeforeTransparentRendering) {
  22457. this.onBeforeTransparentRendering();
  22458. }
  22459. // Transparent
  22460. if (this._transparentSubMeshes.length !== 0) {
  22461. this._renderTransparent(this._transparentSubMeshes);
  22462. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22463. }
  22464. // Set back stencil to false in case it changes before the edge renderer.
  22465. engine.setStencilBuffer(false);
  22466. // Edges
  22467. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22468. this._edgesRenderers.data[edgesRendererIndex].render();
  22469. }
  22470. // Restore Stencil state.
  22471. engine.setStencilBuffer(stencilState);
  22472. };
  22473. /**
  22474. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22475. * @param subMeshes The submeshes to render
  22476. */
  22477. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22478. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22479. };
  22480. /**
  22481. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22482. * @param subMeshes The submeshes to render
  22483. */
  22484. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22485. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22486. };
  22487. /**
  22488. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22489. * @param subMeshes The submeshes to render
  22490. */
  22491. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22492. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22493. };
  22494. /**
  22495. * Renders the submeshes in a specified order.
  22496. * @param subMeshes The submeshes to sort before render
  22497. * @param sortCompareFn The comparison function use to sort
  22498. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22499. * @param transparent Specifies to activate blending if true
  22500. */
  22501. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22502. var subIndex = 0;
  22503. var subMesh;
  22504. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22505. for (; subIndex < subMeshes.length; subIndex++) {
  22506. subMesh = subMeshes.data[subIndex];
  22507. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22508. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22509. }
  22510. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22511. if (sortCompareFn) {
  22512. sortedArray.sort(sortCompareFn);
  22513. }
  22514. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22515. subMesh = sortedArray[subIndex];
  22516. if (transparent) {
  22517. var material = subMesh.getMaterial();
  22518. if (material && material.needDepthPrePass) {
  22519. var engine = material.getScene().getEngine();
  22520. engine.setColorWrite(false);
  22521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22522. subMesh.render(false);
  22523. engine.setColorWrite(true);
  22524. }
  22525. }
  22526. subMesh.render(transparent);
  22527. }
  22528. };
  22529. /**
  22530. * Renders the submeshes in the order they were dispatched (no sort applied).
  22531. * @param subMeshes The submeshes to render
  22532. */
  22533. RenderingGroup.renderUnsorted = function (subMeshes) {
  22534. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22535. var submesh = subMeshes.data[subIndex];
  22536. submesh.render(false);
  22537. }
  22538. };
  22539. /**
  22540. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22541. * are rendered back to front if in the same alpha index.
  22542. *
  22543. * @param a The first submesh
  22544. * @param b The second submesh
  22545. * @returns The result of the comparison
  22546. */
  22547. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22548. // Alpha index first
  22549. if (a._alphaIndex > b._alphaIndex) {
  22550. return 1;
  22551. }
  22552. if (a._alphaIndex < b._alphaIndex) {
  22553. return -1;
  22554. }
  22555. // Then distance to camera
  22556. return RenderingGroup.backToFrontSortCompare(a, b);
  22557. };
  22558. /**
  22559. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22560. * are rendered back to front.
  22561. *
  22562. * @param a The first submesh
  22563. * @param b The second submesh
  22564. * @returns The result of the comparison
  22565. */
  22566. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22567. // Then distance to camera
  22568. if (a._distanceToCamera < b._distanceToCamera) {
  22569. return 1;
  22570. }
  22571. if (a._distanceToCamera > b._distanceToCamera) {
  22572. return -1;
  22573. }
  22574. return 0;
  22575. };
  22576. /**
  22577. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22578. * are rendered front to back (prevent overdraw).
  22579. *
  22580. * @param a The first submesh
  22581. * @param b The second submesh
  22582. * @returns The result of the comparison
  22583. */
  22584. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22585. // Then distance to camera
  22586. if (a._distanceToCamera < b._distanceToCamera) {
  22587. return -1;
  22588. }
  22589. if (a._distanceToCamera > b._distanceToCamera) {
  22590. return 1;
  22591. }
  22592. return 0;
  22593. };
  22594. /**
  22595. * Resets the different lists of submeshes to prepare a new frame.
  22596. */
  22597. RenderingGroup.prototype.prepare = function () {
  22598. this._opaqueSubMeshes.reset();
  22599. this._transparentSubMeshes.reset();
  22600. this._alphaTestSubMeshes.reset();
  22601. this._depthOnlySubMeshes.reset();
  22602. this._particleSystems.reset();
  22603. this._spriteManagers.reset();
  22604. this._edgesRenderers.reset();
  22605. };
  22606. RenderingGroup.prototype.dispose = function () {
  22607. this._opaqueSubMeshes.dispose();
  22608. this._transparentSubMeshes.dispose();
  22609. this._alphaTestSubMeshes.dispose();
  22610. this._depthOnlySubMeshes.dispose();
  22611. this._particleSystems.dispose();
  22612. this._spriteManagers.dispose();
  22613. this._edgesRenderers.dispose();
  22614. };
  22615. /**
  22616. * Inserts the submesh in its correct queue depending on its material.
  22617. * @param subMesh The submesh to dispatch
  22618. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22619. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22620. */
  22621. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22622. // Get mesh and materials if not provided
  22623. if (mesh === undefined) {
  22624. mesh = subMesh.getMesh();
  22625. }
  22626. if (material === undefined) {
  22627. material = subMesh.getMaterial();
  22628. }
  22629. if (material === null || material === undefined) {
  22630. return;
  22631. }
  22632. if (material.needAlphaBlendingForMesh(mesh)) {
  22633. this._transparentSubMeshes.push(subMesh);
  22634. }
  22635. else if (material.needAlphaTesting()) {
  22636. if (material.needDepthPrePass) {
  22637. this._depthOnlySubMeshes.push(subMesh);
  22638. }
  22639. this._alphaTestSubMeshes.push(subMesh);
  22640. }
  22641. else {
  22642. if (material.needDepthPrePass) {
  22643. this._depthOnlySubMeshes.push(subMesh);
  22644. }
  22645. this._opaqueSubMeshes.push(subMesh); // Opaque
  22646. }
  22647. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22648. this._edgesRenderers.push(mesh._edgesRenderer);
  22649. }
  22650. };
  22651. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22652. this._spriteManagers.push(spriteManager);
  22653. };
  22654. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22655. this._particleSystems.push(particleSystem);
  22656. };
  22657. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22658. if (this._particleSystems.length === 0) {
  22659. return;
  22660. }
  22661. // Particles
  22662. var activeCamera = this._scene.activeCamera;
  22663. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22664. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22665. var particleSystem = this._particleSystems.data[particleIndex];
  22666. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22667. continue;
  22668. }
  22669. var emitter = particleSystem.emitter;
  22670. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22671. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22672. }
  22673. }
  22674. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22675. };
  22676. RenderingGroup.prototype._renderSprites = function () {
  22677. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22678. return;
  22679. }
  22680. // Sprites
  22681. var activeCamera = this._scene.activeCamera;
  22682. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22683. for (var id = 0; id < this._spriteManagers.length; id++) {
  22684. var spriteManager = this._spriteManagers.data[id];
  22685. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22686. spriteManager.render();
  22687. }
  22688. }
  22689. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22690. };
  22691. return RenderingGroup;
  22692. }());
  22693. BABYLON.RenderingGroup = RenderingGroup;
  22694. })(BABYLON || (BABYLON = {}));
  22695. //# sourceMappingURL=babylon.renderingGroup.js.map
  22696. "use strict";
  22697. var BABYLON;
  22698. (function (BABYLON) {
  22699. /** @ignore */
  22700. var ClickInfo = /** @class */ (function () {
  22701. function ClickInfo() {
  22702. this._singleClick = false;
  22703. this._doubleClick = false;
  22704. this._hasSwiped = false;
  22705. this._ignore = false;
  22706. }
  22707. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22708. get: function () {
  22709. return this._singleClick;
  22710. },
  22711. set: function (b) {
  22712. this._singleClick = b;
  22713. },
  22714. enumerable: true,
  22715. configurable: true
  22716. });
  22717. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  22718. get: function () {
  22719. return this._doubleClick;
  22720. },
  22721. set: function (b) {
  22722. this._doubleClick = b;
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  22728. get: function () {
  22729. return this._hasSwiped;
  22730. },
  22731. set: function (b) {
  22732. this._hasSwiped = b;
  22733. },
  22734. enumerable: true,
  22735. configurable: true
  22736. });
  22737. Object.defineProperty(ClickInfo.prototype, "ignore", {
  22738. get: function () {
  22739. return this._ignore;
  22740. },
  22741. set: function (b) {
  22742. this._ignore = b;
  22743. },
  22744. enumerable: true,
  22745. configurable: true
  22746. });
  22747. return ClickInfo;
  22748. }());
  22749. /**
  22750. * This class is used by the onRenderingGroupObservable
  22751. */
  22752. var RenderingGroupInfo = /** @class */ (function () {
  22753. function RenderingGroupInfo() {
  22754. }
  22755. /**
  22756. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  22757. * This stage will be fired no matter what
  22758. */
  22759. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  22760. /**
  22761. * Called before opaque object are rendered.
  22762. * This stage will be fired only if there's 3D Opaque content to render
  22763. */
  22764. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  22765. /**
  22766. * Called after the opaque objects are rendered and before the transparent ones
  22767. * This stage will be fired only if there's 3D transparent content to render
  22768. */
  22769. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  22770. /**
  22771. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  22772. * This stage will be fired no matter what
  22773. */
  22774. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  22775. return RenderingGroupInfo;
  22776. }());
  22777. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  22778. /**
  22779. * Represents a scene to be rendered by the engine.
  22780. * @see http://doc.babylonjs.com/features/scene
  22781. */
  22782. var Scene = /** @class */ (function () {
  22783. /**
  22784. * Creates a new Scene
  22785. * @param engine defines the engine to use to render this scene
  22786. */
  22787. function Scene(engine) {
  22788. // Members
  22789. /**
  22790. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  22791. */
  22792. this.autoClear = true;
  22793. /**
  22794. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  22795. */
  22796. this.autoClearDepthAndStencil = true;
  22797. /**
  22798. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  22799. */
  22800. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  22801. /**
  22802. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  22803. */
  22804. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22805. this._forceWireframe = false;
  22806. this._forcePointsCloud = false;
  22807. /**
  22808. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  22809. */
  22810. this.forceShowBoundingBoxes = false;
  22811. /**
  22812. * Gets or sets a boolean indicating if animations are enabled
  22813. */
  22814. this.animationsEnabled = true;
  22815. /**
  22816. * Gets or sets a boolean indicating if a constant deltatime has to be used
  22817. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  22818. */
  22819. this.useConstantAnimationDeltaTime = false;
  22820. /**
  22821. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  22822. * Please note that it requires to run a ray cast through the scene on every frame
  22823. */
  22824. this.constantlyUpdateMeshUnderPointer = false;
  22825. /**
  22826. * Defines the HTML cursor to use when hovering over interactive elements
  22827. */
  22828. this.hoverCursor = "pointer";
  22829. /**
  22830. * Defines the HTML default cursor to use (empty by default)
  22831. */
  22832. this.defaultCursor = "";
  22833. /**
  22834. * This is used to call preventDefault() on pointer down
  22835. * in order to block unwanted artifacts like system double clicks
  22836. */
  22837. this.preventDefaultOnPointerDown = true;
  22838. // Metadata
  22839. /**
  22840. * Gets or sets user defined metadata
  22841. */
  22842. this.metadata = null;
  22843. /**
  22844. * Use this array to add regular expressions used to disable offline support for specific urls
  22845. */
  22846. this.disableOfflineSupportExceptionRules = new Array();
  22847. /**
  22848. * An event triggered when the scene is disposed.
  22849. */
  22850. this.onDisposeObservable = new BABYLON.Observable();
  22851. this._onDisposeObserver = null;
  22852. /**
  22853. * An event triggered before rendering the scene (right after animations and physics)
  22854. */
  22855. this.onBeforeRenderObservable = new BABYLON.Observable();
  22856. this._onBeforeRenderObserver = null;
  22857. /**
  22858. * An event triggered after rendering the scene
  22859. */
  22860. this.onAfterRenderObservable = new BABYLON.Observable();
  22861. this._onAfterRenderObserver = null;
  22862. /**
  22863. * An event triggered before animating the scene
  22864. */
  22865. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  22866. /**
  22867. * An event triggered after animations processing
  22868. */
  22869. this.onAfterAnimationsObservable = new BABYLON.Observable();
  22870. /**
  22871. * An event triggered before draw calls are ready to be sent
  22872. */
  22873. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  22874. /**
  22875. * An event triggered after draw calls have been sent
  22876. */
  22877. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  22878. /**
  22879. * An event triggered when physic simulation is about to be run
  22880. */
  22881. this.onBeforePhysicsObservable = new BABYLON.Observable();
  22882. /**
  22883. * An event triggered when physic simulation has been done
  22884. */
  22885. this.onAfterPhysicsObservable = new BABYLON.Observable();
  22886. /**
  22887. * An event triggered when the scene is ready
  22888. */
  22889. this.onReadyObservable = new BABYLON.Observable();
  22890. /**
  22891. * An event triggered before rendering a camera
  22892. */
  22893. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  22894. this._onBeforeCameraRenderObserver = null;
  22895. /**
  22896. * An event triggered after rendering a camera
  22897. */
  22898. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  22899. this._onAfterCameraRenderObserver = null;
  22900. /**
  22901. * An event triggered when active meshes evaluation is about to start
  22902. */
  22903. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  22904. /**
  22905. * An event triggered when active meshes evaluation is done
  22906. */
  22907. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  22908. /**
  22909. * An event triggered when particles rendering is about to start
  22910. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  22911. */
  22912. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  22913. /**
  22914. * An event triggered when particles rendering is done
  22915. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  22916. */
  22917. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  22918. /**
  22919. * An event triggered when sprites rendering is about to start
  22920. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  22921. */
  22922. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  22923. /**
  22924. * An event triggered when sprites rendering is done
  22925. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  22926. */
  22927. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  22928. /**
  22929. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  22930. */
  22931. this.onDataLoadedObservable = new BABYLON.Observable();
  22932. /**
  22933. * An event triggered when a camera is created
  22934. */
  22935. this.onNewCameraAddedObservable = new BABYLON.Observable();
  22936. /**
  22937. * An event triggered when a camera is removed
  22938. */
  22939. this.onCameraRemovedObservable = new BABYLON.Observable();
  22940. /**
  22941. * An event triggered when a light is created
  22942. */
  22943. this.onNewLightAddedObservable = new BABYLON.Observable();
  22944. /**
  22945. * An event triggered when a light is removed
  22946. */
  22947. this.onLightRemovedObservable = new BABYLON.Observable();
  22948. /**
  22949. * An event triggered when a geometry is created
  22950. */
  22951. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  22952. /**
  22953. * An event triggered when a geometry is removed
  22954. */
  22955. this.onGeometryRemovedObservable = new BABYLON.Observable();
  22956. /**
  22957. * An event triggered when a transform node is created
  22958. */
  22959. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  22960. /**
  22961. * An event triggered when a transform node is removed
  22962. */
  22963. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  22964. /**
  22965. * An event triggered when a mesh is created
  22966. */
  22967. this.onNewMeshAddedObservable = new BABYLON.Observable();
  22968. /**
  22969. * An event triggered when a mesh is removed
  22970. */
  22971. this.onMeshRemovedObservable = new BABYLON.Observable();
  22972. /**
  22973. * An event triggered when render targets are about to be rendered
  22974. * Can happen multiple times per frame.
  22975. */
  22976. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  22977. /**
  22978. * An event triggered when render targets were rendered.
  22979. * Can happen multiple times per frame.
  22980. */
  22981. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  22982. /**
  22983. * An event triggered before calculating deterministic simulation step
  22984. */
  22985. this.onBeforeStepObservable = new BABYLON.Observable();
  22986. /**
  22987. * An event triggered after calculating deterministic simulation step
  22988. */
  22989. this.onAfterStepObservable = new BABYLON.Observable();
  22990. /**
  22991. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  22992. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  22993. * 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)
  22994. */
  22995. this.onRenderingGroupObservable = new BABYLON.Observable();
  22996. // Animations
  22997. /**
  22998. * Gets a list of Animations associated with the scene
  22999. */
  23000. this.animations = [];
  23001. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23002. /**
  23003. * 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).
  23004. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23005. */
  23006. this.onPrePointerObservable = new BABYLON.Observable();
  23007. /**
  23008. * Observable event triggered each time an input event is received from the rendering canvas
  23009. */
  23010. this.onPointerObservable = new BABYLON.Observable();
  23011. this._meshPickProceed = false;
  23012. this._currentPickResult = null;
  23013. this._previousPickResult = null;
  23014. this._totalPointersPressed = 0;
  23015. this._doubleClickOccured = false;
  23016. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23017. this.cameraToUseForPointers = null;
  23018. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23019. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23020. this._startingPointerTime = 0;
  23021. this._previousStartingPointerTime = 0;
  23022. // Deterministic lockstep
  23023. this._timeAccumulator = 0;
  23024. this._currentStepId = 0;
  23025. this._currentInternalStep = 0;
  23026. // Keyboard
  23027. /**
  23028. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23029. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23030. */
  23031. this.onPreKeyboardObservable = new BABYLON.Observable();
  23032. /**
  23033. * Observable event triggered each time an keyboard event is received from the hosting window
  23034. */
  23035. this.onKeyboardObservable = new BABYLON.Observable();
  23036. // Coordinates system
  23037. this._useRightHandedSystem = false;
  23038. // Fog
  23039. this._fogEnabled = true;
  23040. this._fogMode = Scene.FOGMODE_NONE;
  23041. /**
  23042. * Gets or sets the fog color to use
  23043. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23044. */
  23045. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23046. /**
  23047. * Gets or sets the fog density to use
  23048. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23049. */
  23050. this.fogDensity = 0.1;
  23051. /**
  23052. * Gets or sets the fog start distance to use
  23053. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23054. */
  23055. this.fogStart = 0;
  23056. /**
  23057. * Gets or sets the fog end distance to use
  23058. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23059. */
  23060. this.fogEnd = 1000.0;
  23061. // Lights
  23062. this._shadowsEnabled = true;
  23063. this._lightsEnabled = true;
  23064. /**
  23065. * All of the lights added to this scene
  23066. * @see http://doc.babylonjs.com/babylon101/lights
  23067. */
  23068. this.lights = new Array();
  23069. // Cameras
  23070. /** All of the cameras added to this scene.
  23071. * @see http://doc.babylonjs.com/babylon101/cameras
  23072. */
  23073. this.cameras = new Array();
  23074. /** All of the active cameras added to this scene. */
  23075. this.activeCameras = new Array();
  23076. // Meshes
  23077. /**
  23078. * All of the tranform nodes added to this scene
  23079. * @see http://doc.babylonjs.com/how_to/transformnode
  23080. */
  23081. this.transformNodes = new Array();
  23082. /**
  23083. * All of the (abstract) meshes added to this scene
  23084. */
  23085. this.meshes = new Array();
  23086. /**
  23087. * All of the animation groups added to this scene
  23088. * @see http://doc.babylonjs.com/how_to/group
  23089. */
  23090. this.animationGroups = new Array();
  23091. // Geometries
  23092. this._geometries = new Array();
  23093. /**
  23094. * All of the materials added to this scene
  23095. * @see http://doc.babylonjs.com/babylon101/materials
  23096. */
  23097. this.materials = new Array();
  23098. /**
  23099. * All of the multi-materials added to this scene
  23100. * @see http://doc.babylonjs.com/how_to/multi_materials
  23101. */
  23102. this.multiMaterials = new Array();
  23103. // Textures
  23104. this._texturesEnabled = true;
  23105. /**
  23106. * All of the textures added to this scene
  23107. */
  23108. this.textures = new Array();
  23109. // Particles
  23110. /**
  23111. * Gets or sets a boolean indicating if particles are enabled on this scene
  23112. */
  23113. this.particlesEnabled = true;
  23114. /**
  23115. * All of the particle systems added to this scene
  23116. * @see http://doc.babylonjs.com/babylon101/particles
  23117. */
  23118. this.particleSystems = new Array();
  23119. // Sprites
  23120. /**
  23121. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23122. */
  23123. this.spritesEnabled = true;
  23124. /**
  23125. * All of the sprite managers added to this scene
  23126. * @see http://doc.babylonjs.com/babylon101/sprites
  23127. */
  23128. this.spriteManagers = new Array();
  23129. /**
  23130. * The list of layers (background and foreground) of the scene
  23131. */
  23132. this.layers = new Array();
  23133. /**
  23134. * The list of effect layers (highlights/glow) added to the scene
  23135. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23136. * @see http://doc.babylonjs.com/how_to/glow_layer
  23137. */
  23138. this.effectLayers = new Array();
  23139. // Skeletons
  23140. this._skeletonsEnabled = true;
  23141. /**
  23142. * The list of skeletons added to the scene
  23143. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23144. */
  23145. this.skeletons = new Array();
  23146. // Morph targets
  23147. /**
  23148. * The list of morph target managers added to the scene
  23149. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23150. */
  23151. this.morphTargetManagers = new Array();
  23152. // Lens flares
  23153. /**
  23154. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23155. */
  23156. this.lensFlaresEnabled = true;
  23157. /**
  23158. * The list of lens flare system added to the scene
  23159. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23160. */
  23161. this.lensFlareSystems = new Array();
  23162. // Collisions
  23163. /**
  23164. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23165. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23166. */
  23167. this.collisionsEnabled = true;
  23168. /**
  23169. * Defines the gravity applied to this scene (used only for collisions)
  23170. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23171. */
  23172. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23173. // Postprocesses
  23174. /**
  23175. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23176. */
  23177. this.postProcessesEnabled = true;
  23178. /**
  23179. * The list of postprocesses added to the scene
  23180. */
  23181. this.postProcesses = new Array();
  23182. // Customs render targets
  23183. /**
  23184. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23185. */
  23186. this.renderTargetsEnabled = true;
  23187. /**
  23188. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23189. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23190. */
  23191. this.dumpNextRenderTargets = false;
  23192. /**
  23193. * The list of user defined render targets added to the scene
  23194. */
  23195. this.customRenderTargets = new Array();
  23196. /**
  23197. * Gets the list of meshes imported to the scene through SceneLoader
  23198. */
  23199. this.importedMeshesFiles = new Array();
  23200. // Probes
  23201. /**
  23202. * Gets or sets a boolean indicating if probes are enabled on this scene
  23203. */
  23204. this.probesEnabled = true;
  23205. /**
  23206. * The list of reflection probes added to the scene
  23207. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23208. */
  23209. this.reflectionProbes = new Array();
  23210. /** @ignore */
  23211. this._actionManagers = new Array();
  23212. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23213. // Procedural textures
  23214. /**
  23215. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23216. */
  23217. this.proceduralTexturesEnabled = true;
  23218. /**
  23219. * The list of procedural textures added to the scene
  23220. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23221. */
  23222. this.proceduralTextures = new Array();
  23223. /**
  23224. * The list of sound tracks added to the scene
  23225. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23226. */
  23227. this.soundTracks = new Array();
  23228. this._audioEnabled = true;
  23229. this._headphone = false;
  23230. // Performance counters
  23231. this._totalVertices = new BABYLON.PerfCounter();
  23232. /** @ignore */
  23233. this._activeIndices = new BABYLON.PerfCounter();
  23234. /** @ignore */
  23235. this._activeParticles = new BABYLON.PerfCounter();
  23236. /** @ignore */
  23237. this._activeBones = new BABYLON.PerfCounter();
  23238. this._animationTime = 0;
  23239. /**
  23240. * Gets or sets a general scale for animation speed
  23241. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23242. */
  23243. this.animationTimeScale = 1;
  23244. this._renderId = 0;
  23245. this._executeWhenReadyTimeoutId = -1;
  23246. this._intermediateRendering = false;
  23247. this._viewUpdateFlag = -1;
  23248. this._projectionUpdateFlag = -1;
  23249. this._alternateViewUpdateFlag = -1;
  23250. this._alternateProjectionUpdateFlag = -1;
  23251. /** @ignore */
  23252. this._toBeDisposed = new BABYLON.SmartArray(256);
  23253. this._activeRequests = new Array();
  23254. this._pendingData = new Array();
  23255. this._isDisposed = false;
  23256. /**
  23257. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23258. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23259. */
  23260. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23261. this._activeMeshes = new BABYLON.SmartArray(256);
  23262. this._processedMaterials = new BABYLON.SmartArray(256);
  23263. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23264. /** @ignore */
  23265. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23266. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23267. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23268. /** @ignore */
  23269. this._activeAnimatables = new Array();
  23270. this._transformMatrix = BABYLON.Matrix.Zero();
  23271. this._useAlternateCameraConfiguration = false;
  23272. this._alternateRendering = false;
  23273. /**
  23274. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23275. * This is useful if there are more lights that the maximum simulteanous authorized
  23276. */
  23277. this.requireLightSorting = false;
  23278. this._depthRenderer = {};
  23279. this._activeMeshesFrozen = false;
  23280. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23281. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23282. this._engine.scenes.push(this);
  23283. this._uid = null;
  23284. this._renderingManager = new BABYLON.RenderingManager(this);
  23285. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23286. if (BABYLON.OutlineRenderer) {
  23287. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23288. }
  23289. if (BABYLON.Tools.IsWindowObjectExist()) {
  23290. this.attachControl();
  23291. }
  23292. //simplification queue
  23293. if (BABYLON.SimplificationQueue) {
  23294. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23295. }
  23296. //collision coordinator initialization. For now legacy per default.
  23297. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23298. // Uniform Buffer
  23299. this._createUbo();
  23300. // Default Image processing definition.
  23301. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23302. }
  23303. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23304. /** The fog is deactivated */
  23305. get: function () {
  23306. return Scene._FOGMODE_NONE;
  23307. },
  23308. enumerable: true,
  23309. configurable: true
  23310. });
  23311. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23312. /** The fog density is following an exponential function */
  23313. get: function () {
  23314. return Scene._FOGMODE_EXP;
  23315. },
  23316. enumerable: true,
  23317. configurable: true
  23318. });
  23319. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23320. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23321. get: function () {
  23322. return Scene._FOGMODE_EXP2;
  23323. },
  23324. enumerable: true,
  23325. configurable: true
  23326. });
  23327. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23328. /** The fog density is following a linear function. */
  23329. get: function () {
  23330. return Scene._FOGMODE_LINEAR;
  23331. },
  23332. enumerable: true,
  23333. configurable: true
  23334. });
  23335. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23336. /**
  23337. * Texture used in all pbr material as the reflection texture.
  23338. * As in the majority of the scene they are the same (exception for multi room and so on),
  23339. * this is easier to reference from here than from all the materials.
  23340. */
  23341. get: function () {
  23342. return this._environmentTexture;
  23343. },
  23344. /**
  23345. * Texture used in all pbr material as the reflection texture.
  23346. * As in the majority of the scene they are the same (exception for multi room and so on),
  23347. * this is easier to set here than in all the materials.
  23348. */
  23349. set: function (value) {
  23350. if (this._environmentTexture === value) {
  23351. return;
  23352. }
  23353. this._environmentTexture = value;
  23354. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23360. /**
  23361. * Default image processing configuration used either in the rendering
  23362. * Forward main pass or through the imageProcessingPostProcess if present.
  23363. * As in the majority of the scene they are the same (exception for multi camera),
  23364. * this is easier to reference from here than from all the materials and post process.
  23365. *
  23366. * No setter as we it is a shared configuration, you can set the values instead.
  23367. */
  23368. get: function () {
  23369. return this._imageProcessingConfiguration;
  23370. },
  23371. enumerable: true,
  23372. configurable: true
  23373. });
  23374. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23375. get: function () {
  23376. return this._forceWireframe;
  23377. },
  23378. /**
  23379. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23380. */
  23381. set: function (value) {
  23382. if (this._forceWireframe === value) {
  23383. return;
  23384. }
  23385. this._forceWireframe = value;
  23386. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23387. },
  23388. enumerable: true,
  23389. configurable: true
  23390. });
  23391. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23392. get: function () {
  23393. return this._forcePointsCloud;
  23394. },
  23395. /**
  23396. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23397. */
  23398. set: function (value) {
  23399. if (this._forcePointsCloud === value) {
  23400. return;
  23401. }
  23402. this._forcePointsCloud = value;
  23403. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23404. },
  23405. enumerable: true,
  23406. configurable: true
  23407. });
  23408. Object.defineProperty(Scene.prototype, "onDispose", {
  23409. /** Sets a function to be executed when this scene is disposed. */
  23410. set: function (callback) {
  23411. if (this._onDisposeObserver) {
  23412. this.onDisposeObservable.remove(this._onDisposeObserver);
  23413. }
  23414. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23415. },
  23416. enumerable: true,
  23417. configurable: true
  23418. });
  23419. Object.defineProperty(Scene.prototype, "beforeRender", {
  23420. /** Sets a function to be executed before rendering this scene */
  23421. set: function (callback) {
  23422. if (this._onBeforeRenderObserver) {
  23423. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23424. }
  23425. if (callback) {
  23426. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23427. }
  23428. },
  23429. enumerable: true,
  23430. configurable: true
  23431. });
  23432. Object.defineProperty(Scene.prototype, "afterRender", {
  23433. /** Sets a function to be executed after rendering this scene */
  23434. set: function (callback) {
  23435. if (this._onAfterRenderObserver) {
  23436. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23437. }
  23438. if (callback) {
  23439. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23440. }
  23441. },
  23442. enumerable: true,
  23443. configurable: true
  23444. });
  23445. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23446. /** Sets a function to be executed before rendering a camera*/
  23447. set: function (callback) {
  23448. if (this._onBeforeCameraRenderObserver) {
  23449. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23450. }
  23451. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23452. },
  23453. enumerable: true,
  23454. configurable: true
  23455. });
  23456. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23457. /** Sets a function to be executed after rendering a camera*/
  23458. set: function (callback) {
  23459. if (this._onAfterCameraRenderObserver) {
  23460. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23461. }
  23462. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23463. },
  23464. enumerable: true,
  23465. configurable: true
  23466. });
  23467. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23468. /**
  23469. * Gets the gamepad manager associated with the scene
  23470. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23471. */
  23472. get: function () {
  23473. if (!this._gamepadManager) {
  23474. this._gamepadManager = new BABYLON.GamepadManager(this);
  23475. }
  23476. return this._gamepadManager;
  23477. },
  23478. enumerable: true,
  23479. configurable: true
  23480. });
  23481. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23482. /**
  23483. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23484. */
  23485. get: function () {
  23486. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23487. },
  23488. enumerable: true,
  23489. configurable: true
  23490. });
  23491. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23492. get: function () {
  23493. return this._useRightHandedSystem;
  23494. },
  23495. /**
  23496. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23497. */
  23498. set: function (value) {
  23499. if (this._useRightHandedSystem === value) {
  23500. return;
  23501. }
  23502. this._useRightHandedSystem = value;
  23503. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23504. },
  23505. enumerable: true,
  23506. configurable: true
  23507. });
  23508. /**
  23509. * Sets the step Id used by deterministic lock step
  23510. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23511. * @param newStepId defines the step Id
  23512. */
  23513. Scene.prototype.setStepId = function (newStepId) {
  23514. this._currentStepId = newStepId;
  23515. };
  23516. ;
  23517. /**
  23518. * Gets the step Id used by deterministic lock step
  23519. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23520. * @returns the step Id
  23521. */
  23522. Scene.prototype.getStepId = function () {
  23523. return this._currentStepId;
  23524. };
  23525. ;
  23526. /**
  23527. * Gets the internal step used by deterministic lock step
  23528. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23529. * @returns the internal step
  23530. */
  23531. Scene.prototype.getInternalStep = function () {
  23532. return this._currentInternalStep;
  23533. };
  23534. ;
  23535. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23536. get: function () {
  23537. return this._fogEnabled;
  23538. },
  23539. /**
  23540. * Gets or sets a boolean indicating if fog is enabled on this scene
  23541. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23542. */
  23543. set: function (value) {
  23544. if (this._fogEnabled === value) {
  23545. return;
  23546. }
  23547. this._fogEnabled = value;
  23548. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23549. },
  23550. enumerable: true,
  23551. configurable: true
  23552. });
  23553. Object.defineProperty(Scene.prototype, "fogMode", {
  23554. get: function () {
  23555. return this._fogMode;
  23556. },
  23557. /**
  23558. * Gets or sets the fog mode to use
  23559. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23560. */
  23561. set: function (value) {
  23562. if (this._fogMode === value) {
  23563. return;
  23564. }
  23565. this._fogMode = value;
  23566. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23572. get: function () {
  23573. return this._shadowsEnabled;
  23574. },
  23575. /**
  23576. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23577. */
  23578. set: function (value) {
  23579. if (this._shadowsEnabled === value) {
  23580. return;
  23581. }
  23582. this._shadowsEnabled = value;
  23583. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23589. get: function () {
  23590. return this._lightsEnabled;
  23591. },
  23592. /**
  23593. * Gets or sets a boolean indicating if lights are enabled on this scene
  23594. */
  23595. set: function (value) {
  23596. if (this._lightsEnabled === value) {
  23597. return;
  23598. }
  23599. this._lightsEnabled = value;
  23600. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23601. },
  23602. enumerable: true,
  23603. configurable: true
  23604. });
  23605. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23606. /** The default material used on meshes when no material is affected */
  23607. get: function () {
  23608. if (!this._defaultMaterial) {
  23609. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23610. }
  23611. return this._defaultMaterial;
  23612. },
  23613. /** The default material used on meshes when no material is affected */
  23614. set: function (value) {
  23615. this._defaultMaterial = value;
  23616. },
  23617. enumerable: true,
  23618. configurable: true
  23619. });
  23620. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23621. get: function () {
  23622. return this._texturesEnabled;
  23623. },
  23624. /**
  23625. * Gets or sets a boolean indicating if textures are enabled on this scene
  23626. */
  23627. set: function (value) {
  23628. if (this._texturesEnabled === value) {
  23629. return;
  23630. }
  23631. this._texturesEnabled = value;
  23632. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23638. get: function () {
  23639. return this._skeletonsEnabled;
  23640. },
  23641. /**
  23642. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23643. */
  23644. set: function (value) {
  23645. if (this._skeletonsEnabled === value) {
  23646. return;
  23647. }
  23648. this._skeletonsEnabled = value;
  23649. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23650. },
  23651. enumerable: true,
  23652. configurable: true
  23653. });
  23654. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23655. /**
  23656. * Gets the postprocess render pipeline manager
  23657. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23658. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23659. */
  23660. get: function () {
  23661. if (!this._postProcessRenderPipelineManager) {
  23662. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23663. }
  23664. return this._postProcessRenderPipelineManager;
  23665. },
  23666. enumerable: true,
  23667. configurable: true
  23668. });
  23669. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23670. /**
  23671. * Gets the main soundtrack associated with the scene
  23672. */
  23673. get: function () {
  23674. if (!this._mainSoundTrack) {
  23675. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23676. }
  23677. return this._mainSoundTrack;
  23678. },
  23679. enumerable: true,
  23680. configurable: true
  23681. });
  23682. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23683. /** @ignore */
  23684. get: function () {
  23685. return this._alternateRendering;
  23686. },
  23687. enumerable: true,
  23688. configurable: true
  23689. });
  23690. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23691. /**
  23692. * Gets the list of frustum planes (built from the active camera)
  23693. */
  23694. get: function () {
  23695. return this._frustumPlanes;
  23696. },
  23697. enumerable: true,
  23698. configurable: true
  23699. });
  23700. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23701. /**
  23702. * Gets the current geometry buffer associated to the scene.
  23703. */
  23704. get: function () {
  23705. return this._geometryBufferRenderer;
  23706. },
  23707. /**
  23708. * Sets the current geometry buffer for the scene.
  23709. */
  23710. set: function (geometryBufferRenderer) {
  23711. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23712. this._geometryBufferRenderer = geometryBufferRenderer;
  23713. }
  23714. },
  23715. enumerable: true,
  23716. configurable: true
  23717. });
  23718. Object.defineProperty(Scene.prototype, "debugLayer", {
  23719. /**
  23720. * Gets the debug layer associated with the scene
  23721. * @see http://doc.babylonjs.com/features/playground_debuglayer
  23722. */
  23723. get: function () {
  23724. if (!this._debugLayer) {
  23725. this._debugLayer = new BABYLON.DebugLayer(this);
  23726. }
  23727. return this._debugLayer;
  23728. },
  23729. enumerable: true,
  23730. configurable: true
  23731. });
  23732. Object.defineProperty(Scene.prototype, "workerCollisions", {
  23733. /**
  23734. * Gets a boolean indicating if collisions are processed on a web worker
  23735. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  23736. */
  23737. get: function () {
  23738. return this._workerCollisions;
  23739. },
  23740. set: function (enabled) {
  23741. if (!BABYLON.CollisionCoordinatorLegacy) {
  23742. return;
  23743. }
  23744. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  23745. this._workerCollisions = enabled;
  23746. if (this.collisionCoordinator) {
  23747. this.collisionCoordinator.destroy();
  23748. }
  23749. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  23750. this.collisionCoordinator.init(this);
  23751. },
  23752. enumerable: true,
  23753. configurable: true
  23754. });
  23755. Object.defineProperty(Scene.prototype, "selectionOctree", {
  23756. /**
  23757. * Gets the octree used to boost mesh selection (picking)
  23758. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  23759. */
  23760. get: function () {
  23761. return this._selectionOctree;
  23762. },
  23763. enumerable: true,
  23764. configurable: true
  23765. });
  23766. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  23767. /**
  23768. * Gets the mesh that is currently under the pointer
  23769. */
  23770. get: function () {
  23771. return this._pointerOverMesh;
  23772. },
  23773. enumerable: true,
  23774. configurable: true
  23775. });
  23776. Object.defineProperty(Scene.prototype, "pointerX", {
  23777. /**
  23778. * Gets the current on-screen X position of the pointer
  23779. */
  23780. get: function () {
  23781. return this._pointerX;
  23782. },
  23783. enumerable: true,
  23784. configurable: true
  23785. });
  23786. Object.defineProperty(Scene.prototype, "pointerY", {
  23787. /**
  23788. * Gets the current on-screen Y position of the pointer
  23789. */
  23790. get: function () {
  23791. return this._pointerY;
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. /**
  23797. * Gets the cached material (ie. the latest rendered one)
  23798. * @returns the cached material
  23799. */
  23800. Scene.prototype.getCachedMaterial = function () {
  23801. return this._cachedMaterial;
  23802. };
  23803. /**
  23804. * Gets the cached effect (ie. the latest rendered one)
  23805. * @returns the cached effect
  23806. */
  23807. Scene.prototype.getCachedEffect = function () {
  23808. return this._cachedEffect;
  23809. };
  23810. /**
  23811. * Gets the cached visibility state (ie. the latest rendered one)
  23812. * @returns the cached visibility state
  23813. */
  23814. Scene.prototype.getCachedVisibility = function () {
  23815. return this._cachedVisibility;
  23816. };
  23817. /**
  23818. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  23819. * @param material defines the current material
  23820. * @param effect defines the current effect
  23821. * @param visibility defines the current visibility state
  23822. * @returns true if one parameter is not cached
  23823. */
  23824. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  23825. if (visibility === void 0) { visibility = 1; }
  23826. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  23827. };
  23828. /**
  23829. * Gets the bounding box renderer associated with the scene
  23830. * @returns a BoundingBoxRenderer
  23831. */
  23832. Scene.prototype.getBoundingBoxRenderer = function () {
  23833. if (!this._boundingBoxRenderer) {
  23834. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  23835. }
  23836. return this._boundingBoxRenderer;
  23837. };
  23838. /**
  23839. * Gets the outline renderer associated with the scene
  23840. * @returns a OutlineRenderer
  23841. */
  23842. Scene.prototype.getOutlineRenderer = function () {
  23843. return this._outlineRenderer;
  23844. };
  23845. /**
  23846. * Gets the engine associated with the scene
  23847. * @returns an Engine
  23848. */
  23849. Scene.prototype.getEngine = function () {
  23850. return this._engine;
  23851. };
  23852. /**
  23853. * Gets the total number of vertices rendered per frame
  23854. * @returns the total number of vertices rendered per frame
  23855. */
  23856. Scene.prototype.getTotalVertices = function () {
  23857. return this._totalVertices.current;
  23858. };
  23859. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  23860. /**
  23861. * Gets the performance counter for total vertices
  23862. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23863. */
  23864. get: function () {
  23865. return this._totalVertices;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. /**
  23871. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  23872. * @returns the total number of active indices rendered per frame
  23873. */
  23874. Scene.prototype.getActiveIndices = function () {
  23875. return this._activeIndices.current;
  23876. };
  23877. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  23878. /**
  23879. * Gets the performance counter for active indices
  23880. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23881. */
  23882. get: function () {
  23883. return this._activeIndices;
  23884. },
  23885. enumerable: true,
  23886. configurable: true
  23887. });
  23888. /**
  23889. * Gets the total number of active particles rendered per frame
  23890. * @returns the total number of active particles rendered per frame
  23891. */
  23892. Scene.prototype.getActiveParticles = function () {
  23893. return this._activeParticles.current;
  23894. };
  23895. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  23896. /**
  23897. * Gets the performance counter for active particles
  23898. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23899. */
  23900. get: function () {
  23901. return this._activeParticles;
  23902. },
  23903. enumerable: true,
  23904. configurable: true
  23905. });
  23906. /**
  23907. * Gets the total number of active bones rendered per frame
  23908. * @returns the total number of active bones rendered per frame
  23909. */
  23910. Scene.prototype.getActiveBones = function () {
  23911. return this._activeBones.current;
  23912. };
  23913. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  23914. /**
  23915. * Gets the performance counter for active bones
  23916. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23917. */
  23918. get: function () {
  23919. return this._activeBones;
  23920. },
  23921. enumerable: true,
  23922. configurable: true
  23923. });
  23924. /** @ignore */
  23925. Scene.prototype.getInterFramePerfCounter = function () {
  23926. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23927. return 0;
  23928. };
  23929. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  23930. /** @ignore */
  23931. get: function () {
  23932. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23933. return null;
  23934. },
  23935. enumerable: true,
  23936. configurable: true
  23937. });
  23938. /** @ignore */
  23939. Scene.prototype.getLastFrameDuration = function () {
  23940. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  23941. return 0;
  23942. };
  23943. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  23944. /** @ignore */
  23945. get: function () {
  23946. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23947. return null;
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. /** @ignore */
  23953. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  23954. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  23955. return 0;
  23956. };
  23957. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  23958. /** @ignore */
  23959. get: function () {
  23960. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23961. return null;
  23962. },
  23963. enumerable: true,
  23964. configurable: true
  23965. });
  23966. /**
  23967. * Gets the array of active meshes
  23968. * @returns an array of AbstractMesh
  23969. */
  23970. Scene.prototype.getActiveMeshes = function () {
  23971. return this._activeMeshes;
  23972. };
  23973. /** @ignore */
  23974. Scene.prototype.getRenderTargetsDuration = function () {
  23975. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  23976. return 0;
  23977. };
  23978. /** @ignore */
  23979. Scene.prototype.getRenderDuration = function () {
  23980. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  23981. return 0;
  23982. };
  23983. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  23984. /** @ignore */
  23985. get: function () {
  23986. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23987. return null;
  23988. },
  23989. enumerable: true,
  23990. configurable: true
  23991. });
  23992. /** @ignore */
  23993. Scene.prototype.getParticlesDuration = function () {
  23994. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  23995. return 0;
  23996. };
  23997. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  23998. /** @ignore */
  23999. get: function () {
  24000. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24001. return null;
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. /** @ignore */
  24007. Scene.prototype.getSpritesDuration = function () {
  24008. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24009. return 0;
  24010. };
  24011. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24012. /** @ignore */
  24013. get: function () {
  24014. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24015. return null;
  24016. },
  24017. enumerable: true,
  24018. configurable: true
  24019. });
  24020. /**
  24021. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24022. * @returns a number
  24023. */
  24024. Scene.prototype.getAnimationRatio = function () {
  24025. return this._animationRatio;
  24026. };
  24027. /**
  24028. * Gets an unique Id for the current frame
  24029. * @returns a number
  24030. */
  24031. Scene.prototype.getRenderId = function () {
  24032. return this._renderId;
  24033. };
  24034. /** Call this function if you want to manually increment the render Id*/
  24035. Scene.prototype.incrementRenderId = function () {
  24036. this._renderId++;
  24037. };
  24038. Scene.prototype._updatePointerPosition = function (evt) {
  24039. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24040. if (!canvasRect) {
  24041. return;
  24042. }
  24043. this._pointerX = evt.clientX - canvasRect.left;
  24044. this._pointerY = evt.clientY - canvasRect.top;
  24045. this._unTranslatedPointerX = this._pointerX;
  24046. this._unTranslatedPointerY = this._pointerY;
  24047. };
  24048. Scene.prototype._createUbo = function () {
  24049. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24050. this._sceneUbo.addUniform("viewProjection", 16);
  24051. this._sceneUbo.addUniform("view", 16);
  24052. };
  24053. Scene.prototype._createAlternateUbo = function () {
  24054. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24055. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24056. this._alternateSceneUbo.addUniform("view", 16);
  24057. };
  24058. // Pointers handling
  24059. /**
  24060. * Use this method to simulate a pointer move on a mesh
  24061. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24062. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24063. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24064. * @returns the current scene
  24065. */
  24066. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24067. var evt = new PointerEvent("pointermove", pointerEventInit);
  24068. return this._processPointerMove(pickResult, evt);
  24069. };
  24070. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24071. var canvas = this._engine.getRenderingCanvas();
  24072. if (!canvas) {
  24073. return this;
  24074. }
  24075. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24076. this.setPointerOverSprite(null);
  24077. this.setPointerOverMesh(pickResult.pickedMesh);
  24078. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24079. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24080. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24081. }
  24082. else {
  24083. canvas.style.cursor = this.hoverCursor;
  24084. }
  24085. }
  24086. else {
  24087. canvas.style.cursor = this.defaultCursor;
  24088. }
  24089. }
  24090. else {
  24091. this.setPointerOverMesh(null);
  24092. // Sprites
  24093. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24094. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24095. this.setPointerOverSprite(pickResult.pickedSprite);
  24096. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24097. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24098. }
  24099. else {
  24100. canvas.style.cursor = this.hoverCursor;
  24101. }
  24102. }
  24103. else {
  24104. this.setPointerOverSprite(null);
  24105. // Restore pointer
  24106. canvas.style.cursor = this.defaultCursor;
  24107. }
  24108. }
  24109. if (pickResult) {
  24110. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24111. if (this.onPointerMove) {
  24112. this.onPointerMove(evt, pickResult, type);
  24113. }
  24114. if (this.onPointerObservable.hasObservers()) {
  24115. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24116. this.onPointerObservable.notifyObservers(pi, type);
  24117. }
  24118. }
  24119. return this;
  24120. };
  24121. /**
  24122. * Use this method to simulate a pointer down on a mesh
  24123. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24124. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24125. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24126. * @returns the current scene
  24127. */
  24128. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24129. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24130. return this._processPointerDown(pickResult, evt);
  24131. };
  24132. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24133. var _this = this;
  24134. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24135. this._pickedDownMesh = pickResult.pickedMesh;
  24136. var actionManager = pickResult.pickedMesh.actionManager;
  24137. if (actionManager) {
  24138. if (actionManager.hasPickTriggers) {
  24139. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24140. switch (evt.button) {
  24141. case 0:
  24142. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24143. break;
  24144. case 1:
  24145. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24146. break;
  24147. case 2:
  24148. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24149. break;
  24150. }
  24151. }
  24152. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24153. window.setTimeout(function () {
  24154. 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);
  24155. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24156. if (_this._totalPointersPressed !== 0 &&
  24157. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24158. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24159. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24160. _this._startingPointerTime = 0;
  24161. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24162. }
  24163. }
  24164. }, Scene.LongPressDelay);
  24165. }
  24166. }
  24167. }
  24168. if (pickResult) {
  24169. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24170. if (this.onPointerDown) {
  24171. this.onPointerDown(evt, pickResult, type);
  24172. }
  24173. if (this.onPointerObservable.hasObservers()) {
  24174. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24175. this.onPointerObservable.notifyObservers(pi, type);
  24176. }
  24177. }
  24178. return this;
  24179. };
  24180. /**
  24181. * Use this method to simulate a pointer up on a mesh
  24182. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24183. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24184. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24185. * @returns the current scene
  24186. */
  24187. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24188. var evt = new PointerEvent("pointerup", pointerEventInit);
  24189. var clickInfo = new ClickInfo();
  24190. clickInfo.singleClick = true;
  24191. clickInfo.ignore = true;
  24192. return this._processPointerUp(pickResult, evt, clickInfo);
  24193. };
  24194. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24195. if (pickResult && pickResult && pickResult.pickedMesh) {
  24196. this._pickedUpMesh = pickResult.pickedMesh;
  24197. if (this._pickedDownMesh === this._pickedUpMesh) {
  24198. if (this.onPointerPick) {
  24199. this.onPointerPick(evt, pickResult);
  24200. }
  24201. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24202. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24203. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24204. this.onPointerObservable.notifyObservers(pi, type_1);
  24205. }
  24206. }
  24207. if (pickResult.pickedMesh.actionManager) {
  24208. if (clickInfo.ignore) {
  24209. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24210. }
  24211. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24212. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24213. }
  24214. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24215. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24216. }
  24217. }
  24218. }
  24219. if (this._pickedDownMesh &&
  24220. this._pickedDownMesh.actionManager &&
  24221. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24222. this._pickedDownMesh !== this._pickedUpMesh) {
  24223. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24224. }
  24225. var type = BABYLON.PointerEventTypes.POINTERUP;
  24226. if (this.onPointerObservable.hasObservers()) {
  24227. if (!clickInfo.ignore) {
  24228. if (!clickInfo.hasSwiped) {
  24229. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24230. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24231. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24232. this.onPointerObservable.notifyObservers(pi, type_2);
  24233. }
  24234. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24235. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24236. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24237. this.onPointerObservable.notifyObservers(pi, type_3);
  24238. }
  24239. }
  24240. }
  24241. else {
  24242. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24243. this.onPointerObservable.notifyObservers(pi, type);
  24244. }
  24245. }
  24246. if (this.onPointerUp) {
  24247. this.onPointerUp(evt, pickResult, type);
  24248. }
  24249. return this;
  24250. };
  24251. /**
  24252. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24253. * @param attachUp defines if you want to attach events to pointerup
  24254. * @param attachDown defines if you want to attach events to pointerdown
  24255. * @param attachMove defines if you want to attach events to pointermove
  24256. */
  24257. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24258. var _this = this;
  24259. if (attachUp === void 0) { attachUp = true; }
  24260. if (attachDown === void 0) { attachDown = true; }
  24261. if (attachMove === void 0) { attachMove = true; }
  24262. this._initActionManager = function (act, clickInfo) {
  24263. if (!_this._meshPickProceed) {
  24264. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24265. _this._currentPickResult = pickResult;
  24266. if (pickResult) {
  24267. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24268. }
  24269. _this._meshPickProceed = true;
  24270. }
  24271. return act;
  24272. };
  24273. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24274. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24275. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24276. btn !== _this._previousButtonPressed) {
  24277. _this._doubleClickOccured = false;
  24278. clickInfo.singleClick = true;
  24279. clickInfo.ignore = false;
  24280. cb(clickInfo, _this._currentPickResult);
  24281. }
  24282. };
  24283. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24284. var clickInfo = new ClickInfo();
  24285. _this._currentPickResult = null;
  24286. var act = null;
  24287. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24288. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24289. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24290. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24291. act = _this._initActionManager(act, clickInfo);
  24292. if (act)
  24293. checkPicking = act.hasPickTriggers;
  24294. }
  24295. if (checkPicking) {
  24296. var btn = evt.button;
  24297. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24298. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24299. if (!clickInfo.hasSwiped) {
  24300. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24301. if (!checkSingleClickImmediately) {
  24302. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24303. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24304. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24305. act = _this._initActionManager(act, clickInfo);
  24306. if (act)
  24307. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24308. }
  24309. }
  24310. if (checkSingleClickImmediately) {
  24311. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24312. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24313. btn !== _this._previousButtonPressed) {
  24314. clickInfo.singleClick = true;
  24315. cb(clickInfo, _this._currentPickResult);
  24316. }
  24317. }
  24318. else {
  24319. // wait that no double click has been raised during the double click delay
  24320. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24321. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24322. }
  24323. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24324. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24325. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24326. act = _this._initActionManager(act, clickInfo);
  24327. if (act)
  24328. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24329. }
  24330. if (checkDoubleClick) {
  24331. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24332. if (btn === _this._previousButtonPressed &&
  24333. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24334. !_this._doubleClickOccured) {
  24335. // pointer has not moved for 2 clicks, it's a double click
  24336. if (!clickInfo.hasSwiped &&
  24337. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24338. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24339. _this._previousStartingPointerTime = 0;
  24340. _this._doubleClickOccured = true;
  24341. clickInfo.doubleClick = true;
  24342. clickInfo.ignore = false;
  24343. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24344. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24345. }
  24346. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24347. cb(clickInfo, _this._currentPickResult);
  24348. }
  24349. else {
  24350. _this._doubleClickOccured = false;
  24351. _this._previousStartingPointerTime = _this._startingPointerTime;
  24352. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24353. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24354. _this._previousButtonPressed = btn;
  24355. if (Scene.ExclusiveDoubleClickMode) {
  24356. if (_this._previousDelayedSimpleClickTimeout) {
  24357. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24358. }
  24359. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24360. cb(clickInfo, _this._previousPickResult);
  24361. }
  24362. else {
  24363. cb(clickInfo, _this._currentPickResult);
  24364. }
  24365. }
  24366. }
  24367. else {
  24368. _this._doubleClickOccured = false;
  24369. _this._previousStartingPointerTime = _this._startingPointerTime;
  24370. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24371. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24372. _this._previousButtonPressed = btn;
  24373. }
  24374. }
  24375. }
  24376. }
  24377. clickInfo.ignore = true;
  24378. cb(clickInfo, _this._currentPickResult);
  24379. };
  24380. this._spritePredicate = function (sprite) {
  24381. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24382. };
  24383. this._onPointerMove = function (evt) {
  24384. _this._updatePointerPosition(evt);
  24385. // PreObservable support
  24386. if (_this.onPrePointerObservable.hasObservers()) {
  24387. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24388. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24389. _this.onPrePointerObservable.notifyObservers(pi, type);
  24390. if (pi.skipOnPointerObservable) {
  24391. return;
  24392. }
  24393. }
  24394. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24395. return;
  24396. }
  24397. if (!_this.pointerMovePredicate) {
  24398. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24399. }
  24400. // Meshes
  24401. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24402. _this._processPointerMove(pickResult, evt);
  24403. };
  24404. this._onPointerDown = function (evt) {
  24405. _this._totalPointersPressed++;
  24406. _this._pickedDownMesh = null;
  24407. _this._meshPickProceed = false;
  24408. _this._updatePointerPosition(evt);
  24409. if (_this.preventDefaultOnPointerDown && canvas) {
  24410. evt.preventDefault();
  24411. canvas.focus();
  24412. }
  24413. // PreObservable support
  24414. if (_this.onPrePointerObservable.hasObservers()) {
  24415. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24416. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24417. _this.onPrePointerObservable.notifyObservers(pi, type);
  24418. if (pi.skipOnPointerObservable) {
  24419. return;
  24420. }
  24421. }
  24422. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24423. return;
  24424. }
  24425. _this._startingPointerPosition.x = _this._pointerX;
  24426. _this._startingPointerPosition.y = _this._pointerY;
  24427. _this._startingPointerTime = new Date().getTime();
  24428. if (!_this.pointerDownPredicate) {
  24429. _this.pointerDownPredicate = function (mesh) {
  24430. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24431. };
  24432. }
  24433. // Meshes
  24434. _this._pickedDownMesh = null;
  24435. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24436. _this._processPointerDown(pickResult, evt);
  24437. // Sprites
  24438. _this._pickedDownSprite = null;
  24439. if (_this.spriteManagers.length > 0) {
  24440. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24441. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24442. if (pickResult.pickedSprite.actionManager) {
  24443. _this._pickedDownSprite = pickResult.pickedSprite;
  24444. switch (evt.button) {
  24445. case 0:
  24446. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24447. break;
  24448. case 1:
  24449. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24450. break;
  24451. case 2:
  24452. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24453. break;
  24454. }
  24455. if (pickResult.pickedSprite.actionManager) {
  24456. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24457. }
  24458. }
  24459. }
  24460. }
  24461. };
  24462. this._onPointerUp = function (evt) {
  24463. if (_this._totalPointersPressed === 0) {
  24464. return; // So we need to test it the pointer down was pressed before.
  24465. }
  24466. _this._totalPointersPressed--;
  24467. _this._pickedUpMesh = null;
  24468. _this._meshPickProceed = false;
  24469. _this._updatePointerPosition(evt);
  24470. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24471. // PreObservable support
  24472. if (_this.onPrePointerObservable.hasObservers()) {
  24473. if (!clickInfo.ignore) {
  24474. if (!clickInfo.hasSwiped) {
  24475. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24476. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24477. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24478. _this.onPrePointerObservable.notifyObservers(pi, type);
  24479. if (pi.skipOnPointerObservable) {
  24480. return;
  24481. }
  24482. }
  24483. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24484. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24485. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24486. _this.onPrePointerObservable.notifyObservers(pi, type);
  24487. if (pi.skipOnPointerObservable) {
  24488. return;
  24489. }
  24490. }
  24491. }
  24492. }
  24493. else {
  24494. var type = BABYLON.PointerEventTypes.POINTERUP;
  24495. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24496. _this.onPrePointerObservable.notifyObservers(pi, type);
  24497. if (pi.skipOnPointerObservable) {
  24498. return;
  24499. }
  24500. }
  24501. }
  24502. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24503. return;
  24504. }
  24505. if (!_this.pointerUpPredicate) {
  24506. _this.pointerUpPredicate = function (mesh) {
  24507. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24508. };
  24509. }
  24510. // Meshes
  24511. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24512. _this._initActionManager(null, clickInfo);
  24513. }
  24514. if (!pickResult) {
  24515. pickResult = _this._currentPickResult;
  24516. }
  24517. _this._processPointerUp(pickResult, evt, clickInfo);
  24518. // Sprites
  24519. if (_this.spriteManagers.length > 0) {
  24520. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24521. if (spritePickResult) {
  24522. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24523. if (spritePickResult.pickedSprite.actionManager) {
  24524. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24525. if (spritePickResult.pickedSprite.actionManager) {
  24526. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24527. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24528. }
  24529. }
  24530. }
  24531. }
  24532. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24533. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24534. }
  24535. }
  24536. }
  24537. _this._previousPickResult = _this._currentPickResult;
  24538. });
  24539. };
  24540. this._onKeyDown = function (evt) {
  24541. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24542. if (_this.onPreKeyboardObservable.hasObservers()) {
  24543. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24544. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24545. if (pi.skipOnPointerObservable) {
  24546. return;
  24547. }
  24548. }
  24549. if (_this.onKeyboardObservable.hasObservers()) {
  24550. var pi = new BABYLON.KeyboardInfo(type, evt);
  24551. _this.onKeyboardObservable.notifyObservers(pi, type);
  24552. }
  24553. if (_this.actionManager) {
  24554. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24555. }
  24556. };
  24557. this._onKeyUp = function (evt) {
  24558. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24559. if (_this.onPreKeyboardObservable.hasObservers()) {
  24560. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24561. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24562. if (pi.skipOnPointerObservable) {
  24563. return;
  24564. }
  24565. }
  24566. if (_this.onKeyboardObservable.hasObservers()) {
  24567. var pi = new BABYLON.KeyboardInfo(type, evt);
  24568. _this.onKeyboardObservable.notifyObservers(pi, type);
  24569. }
  24570. if (_this.actionManager) {
  24571. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24572. }
  24573. };
  24574. var engine = this.getEngine();
  24575. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24576. if (!canvas) {
  24577. return;
  24578. }
  24579. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24580. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24581. });
  24582. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24583. if (!canvas) {
  24584. return;
  24585. }
  24586. canvas.removeEventListener("keydown", _this._onKeyDown);
  24587. canvas.removeEventListener("keyup", _this._onKeyUp);
  24588. });
  24589. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24590. var canvas = this._engine.getRenderingCanvas();
  24591. if (!canvas) {
  24592. return;
  24593. }
  24594. if (attachMove) {
  24595. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24596. // Wheel
  24597. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24598. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24599. }
  24600. if (attachDown) {
  24601. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24602. }
  24603. if (attachUp) {
  24604. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24605. }
  24606. canvas.tabIndex = 1;
  24607. };
  24608. /** Detaches all event handlers*/
  24609. Scene.prototype.detachControl = function () {
  24610. var engine = this.getEngine();
  24611. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24612. var canvas = engine.getRenderingCanvas();
  24613. if (!canvas) {
  24614. return;
  24615. }
  24616. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24617. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24618. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24619. if (this._onCanvasBlurObserver) {
  24620. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24621. }
  24622. if (this._onCanvasFocusObserver) {
  24623. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24624. }
  24625. // Wheel
  24626. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24627. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24628. // Keyboard
  24629. canvas.removeEventListener("keydown", this._onKeyDown);
  24630. canvas.removeEventListener("keyup", this._onKeyUp);
  24631. // Observables
  24632. this.onKeyboardObservable.clear();
  24633. this.onPreKeyboardObservable.clear();
  24634. this.onPointerObservable.clear();
  24635. this.onPrePointerObservable.clear();
  24636. };
  24637. /**
  24638. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24639. * Delay loaded resources are not taking in account
  24640. * @return true if all required resources are ready
  24641. */
  24642. Scene.prototype.isReady = function () {
  24643. if (this._isDisposed) {
  24644. return false;
  24645. }
  24646. if (this._pendingData.length > 0) {
  24647. return false;
  24648. }
  24649. var index;
  24650. var engine = this.getEngine();
  24651. // Geometries
  24652. for (index = 0; index < this._geometries.length; index++) {
  24653. var geometry = this._geometries[index];
  24654. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24655. return false;
  24656. }
  24657. }
  24658. // Meshes
  24659. for (index = 0; index < this.meshes.length; index++) {
  24660. var mesh = this.meshes[index];
  24661. if (!mesh.isEnabled()) {
  24662. continue;
  24663. }
  24664. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24665. continue;
  24666. }
  24667. if (!mesh.isReady(true)) {
  24668. return false;
  24669. }
  24670. // Effect layers
  24671. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24672. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24673. var layer = _a[_i];
  24674. if (!layer.hasMesh(mesh)) {
  24675. continue;
  24676. }
  24677. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24678. var subMesh = _c[_b];
  24679. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24680. return false;
  24681. }
  24682. }
  24683. }
  24684. }
  24685. // Post-processes
  24686. if (this.activeCameras && this.activeCameras.length > 0) {
  24687. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24688. var camera = _e[_d];
  24689. if (!camera.isReady(true)) {
  24690. return false;
  24691. }
  24692. }
  24693. }
  24694. else if (this.activeCamera) {
  24695. if (!this.activeCamera.isReady(true)) {
  24696. return false;
  24697. }
  24698. }
  24699. // Particles
  24700. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24701. var particleSystem = _g[_f];
  24702. if (!particleSystem.isReady()) {
  24703. return false;
  24704. }
  24705. }
  24706. return true;
  24707. };
  24708. /** Resets all cached information relative to material (including effect and visibility) */
  24709. Scene.prototype.resetCachedMaterial = function () {
  24710. this._cachedMaterial = null;
  24711. this._cachedEffect = null;
  24712. this._cachedVisibility = null;
  24713. };
  24714. /**
  24715. * Registers a function to be called before every frame render
  24716. * @param func defines the function to register
  24717. */
  24718. Scene.prototype.registerBeforeRender = function (func) {
  24719. this.onBeforeRenderObservable.add(func);
  24720. };
  24721. /**
  24722. * Unregisters a function called before every frame render
  24723. * @param func defines the function to unregister
  24724. */
  24725. Scene.prototype.unregisterBeforeRender = function (func) {
  24726. this.onBeforeRenderObservable.removeCallback(func);
  24727. };
  24728. /**
  24729. * Registers a function to be called after every frame render
  24730. * @param func defines the function to register
  24731. */
  24732. Scene.prototype.registerAfterRender = function (func) {
  24733. this.onAfterRenderObservable.add(func);
  24734. };
  24735. /**
  24736. * Unregisters a function called after every frame render
  24737. * @param func defines the function to unregister
  24738. */
  24739. Scene.prototype.unregisterAfterRender = function (func) {
  24740. this.onAfterRenderObservable.removeCallback(func);
  24741. };
  24742. Scene.prototype._executeOnceBeforeRender = function (func) {
  24743. var _this = this;
  24744. var execFunc = function () {
  24745. func();
  24746. setTimeout(function () {
  24747. _this.unregisterBeforeRender(execFunc);
  24748. });
  24749. };
  24750. this.registerBeforeRender(execFunc);
  24751. };
  24752. /**
  24753. * The provided function will run before render once and will be disposed afterwards.
  24754. * A timeout delay can be provided so that the function will be executed in N ms.
  24755. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  24756. * @param func The function to be executed.
  24757. * @param timeout optional delay in ms
  24758. */
  24759. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  24760. var _this = this;
  24761. if (timeout !== undefined) {
  24762. setTimeout(function () {
  24763. _this._executeOnceBeforeRender(func);
  24764. }, timeout);
  24765. }
  24766. else {
  24767. this._executeOnceBeforeRender(func);
  24768. }
  24769. };
  24770. /** @ignore */
  24771. Scene.prototype._addPendingData = function (data) {
  24772. this._pendingData.push(data);
  24773. };
  24774. /** @ignore */
  24775. Scene.prototype._removePendingData = function (data) {
  24776. var wasLoading = this.isLoading;
  24777. var index = this._pendingData.indexOf(data);
  24778. if (index !== -1) {
  24779. this._pendingData.splice(index, 1);
  24780. }
  24781. if (wasLoading && !this.isLoading) {
  24782. this.onDataLoadedObservable.notifyObservers(this);
  24783. }
  24784. };
  24785. /**
  24786. * Returns the number of items waiting to be loaded
  24787. * @returns the number of items waiting to be loaded
  24788. */
  24789. Scene.prototype.getWaitingItemsCount = function () {
  24790. return this._pendingData.length;
  24791. };
  24792. Object.defineProperty(Scene.prototype, "isLoading", {
  24793. /**
  24794. * Returns a boolean indicating if the scene is still loading data
  24795. */
  24796. get: function () {
  24797. return this._pendingData.length > 0;
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. /**
  24803. * Registers a function to be executed when the scene is ready
  24804. * @param {Function} func - the function to be executed
  24805. */
  24806. Scene.prototype.executeWhenReady = function (func) {
  24807. var _this = this;
  24808. this.onReadyObservable.add(func);
  24809. if (this._executeWhenReadyTimeoutId !== -1) {
  24810. return;
  24811. }
  24812. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24813. _this._checkIsReady();
  24814. }, 150);
  24815. };
  24816. /**
  24817. * Returns a promise that resolves when the scene is ready
  24818. * @returns A promise that resolves when the scene is ready
  24819. */
  24820. Scene.prototype.whenReadyAsync = function () {
  24821. var _this = this;
  24822. return new Promise(function (resolve) {
  24823. _this.executeWhenReady(function () {
  24824. resolve();
  24825. });
  24826. });
  24827. };
  24828. /** @ignore */
  24829. Scene.prototype._checkIsReady = function () {
  24830. var _this = this;
  24831. if (this.isReady()) {
  24832. this.onReadyObservable.notifyObservers(this);
  24833. this.onReadyObservable.clear();
  24834. this._executeWhenReadyTimeoutId = -1;
  24835. return;
  24836. }
  24837. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24838. _this._checkIsReady();
  24839. }, 150);
  24840. };
  24841. // Animations
  24842. /**
  24843. * Will start the animation sequence of a given target
  24844. * @param target defines the target
  24845. * @param from defines from which frame should animation start
  24846. * @param to defines until which frame should animation run.
  24847. * @param weight defines the weight to apply to the animation (1.0 by default)
  24848. * @param loop defines if the animation loops
  24849. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  24850. * @param onAnimationEnd defines the function to be executed when the animation ends
  24851. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  24852. * @returns the animatable object created for this animation
  24853. */
  24854. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  24855. if (weight === void 0) { weight = 1.0; }
  24856. if (speedRatio === void 0) { speedRatio = 1.0; }
  24857. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  24858. returnedAnimatable.weight = weight;
  24859. return returnedAnimatable;
  24860. };
  24861. /**
  24862. * Will start the animation sequence of a given target
  24863. * @param target defines the target
  24864. * @param from defines from which frame should animation start
  24865. * @param to defines until which frame should animation run.
  24866. * @param loop defines if the animation loops
  24867. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  24868. * @param onAnimationEnd defines the function to be executed when the animation ends
  24869. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  24870. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  24871. * @returns the animatable object created for this animation
  24872. */
  24873. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  24874. if (speedRatio === void 0) { speedRatio = 1.0; }
  24875. if (stopCurrent === void 0) { stopCurrent = true; }
  24876. if (from > to && speedRatio > 0) {
  24877. speedRatio *= -1;
  24878. }
  24879. if (stopCurrent) {
  24880. this.stopAnimation(target);
  24881. }
  24882. if (!animatable) {
  24883. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  24884. }
  24885. // Local animations
  24886. if (target.animations) {
  24887. animatable.appendAnimations(target, target.animations);
  24888. }
  24889. // Children animations
  24890. if (target.getAnimatables) {
  24891. var animatables = target.getAnimatables();
  24892. for (var index = 0; index < animatables.length; index++) {
  24893. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  24894. }
  24895. }
  24896. animatable.reset();
  24897. return animatable;
  24898. };
  24899. /**
  24900. * Begin a new animation on a given node
  24901. * @param target defines the target where the animation will take place
  24902. * @param animations defines the list of animations to start
  24903. * @param from defines the initial value
  24904. * @param to defines the final value
  24905. * @param loop defines if you want animation to loop (off by default)
  24906. * @param speedRatio defines the speed ratio to apply to all animations
  24907. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  24908. * @returns the list of created animatables
  24909. */
  24910. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  24911. if (speedRatio === undefined) {
  24912. speedRatio = 1.0;
  24913. }
  24914. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  24915. return animatable;
  24916. };
  24917. /**
  24918. * Begin a new animation on a given node and its hierarchy
  24919. * @param target defines the root node where the animation will take place
  24920. * @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.
  24921. * @param animations defines the list of animations to start
  24922. * @param from defines the initial value
  24923. * @param to defines the final value
  24924. * @param loop defines if you want animation to loop (off by default)
  24925. * @param speedRatio defines the speed ratio to apply to all animations
  24926. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  24927. * @returns the list of animatables created for all nodes
  24928. */
  24929. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  24930. var children = target.getDescendants(directDescendantsOnly);
  24931. var result = [];
  24932. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  24933. var child = children_1[_i];
  24934. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  24935. }
  24936. return result;
  24937. };
  24938. /**
  24939. * Gets the animatable associated with a specific target
  24940. * @param target defines the target of the animatable
  24941. * @returns the required animatable if found
  24942. */
  24943. Scene.prototype.getAnimatableByTarget = function (target) {
  24944. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24945. if (this._activeAnimatables[index].target === target) {
  24946. return this._activeAnimatables[index];
  24947. }
  24948. }
  24949. return null;
  24950. };
  24951. /**
  24952. * Gets all animatables associated with a given target
  24953. * @param target defines the target to look animatables for
  24954. * @returns an array of Animatables
  24955. */
  24956. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  24957. var result = [];
  24958. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24959. if (this._activeAnimatables[index].target === target) {
  24960. result.push(this._activeAnimatables[index]);
  24961. }
  24962. }
  24963. return result;
  24964. };
  24965. Object.defineProperty(Scene.prototype, "animatables", {
  24966. /**
  24967. * Gets all animatable attached to the scene
  24968. */
  24969. get: function () {
  24970. return this._activeAnimatables;
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. /**
  24976. * Will stop the animation of the given target
  24977. * @param target - the target
  24978. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  24979. */
  24980. Scene.prototype.stopAnimation = function (target, animationName) {
  24981. var animatables = this.getAllAnimatablesByTarget(target);
  24982. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  24983. var animatable = animatables_1[_i];
  24984. animatable.stop(animationName);
  24985. }
  24986. };
  24987. /**
  24988. * Stops and removes all animations that have been applied to the scene
  24989. */
  24990. Scene.prototype.stopAllAnimations = function () {
  24991. if (this._activeAnimatables) {
  24992. for (var i = 0; i < this._activeAnimatables.length; i++) {
  24993. this._activeAnimatables[i].stop();
  24994. }
  24995. this._activeAnimatables = [];
  24996. }
  24997. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  24998. var group = _a[_i];
  24999. group.stop();
  25000. }
  25001. };
  25002. Scene.prototype._animate = function () {
  25003. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25004. return;
  25005. }
  25006. // Getting time
  25007. var now = BABYLON.Tools.Now;
  25008. if (!this._animationTimeLast) {
  25009. if (this._pendingData.length > 0) {
  25010. return;
  25011. }
  25012. this._animationTimeLast = now;
  25013. }
  25014. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25015. this._animationTime += deltaTime;
  25016. this._animationTimeLast = now;
  25017. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25018. this._activeAnimatables[index]._animate(this._animationTime);
  25019. }
  25020. // Late animation bindings
  25021. this._processLateAnimationBindings();
  25022. };
  25023. /** @ignore */
  25024. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25025. var target = runtimeAnimation.target;
  25026. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25027. if (!target._lateAnimationHolders) {
  25028. target._lateAnimationHolders = {};
  25029. }
  25030. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25031. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25032. totalWeight: 0,
  25033. animations: []
  25034. };
  25035. }
  25036. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25037. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25038. };
  25039. Scene.prototype._processLateAnimationBindings = function () {
  25040. if (!this._registeredForLateAnimationBindings.length) {
  25041. return;
  25042. }
  25043. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25044. var target = this._registeredForLateAnimationBindings.data[index];
  25045. for (var path in target._lateAnimationHolders) {
  25046. var holder = target._lateAnimationHolders[path];
  25047. // Sanity check
  25048. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  25049. continue;
  25050. }
  25051. var normalizer = 1.0;
  25052. var finalValue = void 0;
  25053. if (holder.totalWeight < 1.0) {
  25054. // We need to mix the original value in
  25055. var originalValue = holder.animations[0].originalValue;
  25056. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25057. }
  25058. else {
  25059. // We need to normalize the weights
  25060. normalizer = holder.totalWeight;
  25061. }
  25062. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25063. var runtimeAnimation = holder.animations[animIndex];
  25064. if (finalValue) {
  25065. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  25066. }
  25067. else {
  25068. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  25069. }
  25070. }
  25071. runtimeAnimation.target[path] = finalValue;
  25072. }
  25073. target._lateAnimationHolders = {};
  25074. }
  25075. this._registeredForLateAnimationBindings.reset();
  25076. };
  25077. // Matrix
  25078. /** @ignore */
  25079. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25080. this._useAlternateCameraConfiguration = active;
  25081. };
  25082. /**
  25083. * Gets the current view matrix
  25084. * @returns a Matrix
  25085. */
  25086. Scene.prototype.getViewMatrix = function () {
  25087. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25088. };
  25089. /**
  25090. * Gets the current projection matrix
  25091. * @returns a Matrix
  25092. */
  25093. Scene.prototype.getProjectionMatrix = function () {
  25094. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25095. };
  25096. /**
  25097. * Gets the current transform matrix
  25098. * @returns a Matrix made of View * Projection
  25099. */
  25100. Scene.prototype.getTransformMatrix = function () {
  25101. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25102. };
  25103. /**
  25104. * Sets the current transform matrix
  25105. * @param view defines the View matrix to use
  25106. * @param projection defines the Projection matrix to use
  25107. */
  25108. Scene.prototype.setTransformMatrix = function (view, projection) {
  25109. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25110. return;
  25111. }
  25112. this._viewUpdateFlag = view.updateFlag;
  25113. this._projectionUpdateFlag = projection.updateFlag;
  25114. this._viewMatrix = view;
  25115. this._projectionMatrix = projection;
  25116. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25117. // Update frustum
  25118. if (!this._frustumPlanes) {
  25119. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25120. }
  25121. else {
  25122. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25123. }
  25124. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25125. var otherCamera = this.activeCamera._alternateCamera;
  25126. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25127. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25128. }
  25129. if (this._sceneUbo.useUbo) {
  25130. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25131. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25132. this._sceneUbo.update();
  25133. }
  25134. };
  25135. /** @ignore */
  25136. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25137. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25138. return;
  25139. }
  25140. this._alternateViewUpdateFlag = view.updateFlag;
  25141. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25142. this._alternateViewMatrix = view;
  25143. this._alternateProjectionMatrix = projection;
  25144. if (!this._alternateTransformMatrix) {
  25145. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25146. }
  25147. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25148. if (!this._alternateSceneUbo) {
  25149. this._createAlternateUbo();
  25150. }
  25151. if (this._alternateSceneUbo.useUbo) {
  25152. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25153. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25154. this._alternateSceneUbo.update();
  25155. }
  25156. };
  25157. /**
  25158. * Gets the uniform buffer used to store scene data
  25159. * @returns a UniformBuffer
  25160. */
  25161. Scene.prototype.getSceneUniformBuffer = function () {
  25162. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25163. };
  25164. /**
  25165. * Gets an unique (relatively to the current scene) Id
  25166. * @returns an unique number for the scene
  25167. */
  25168. Scene.prototype.getUniqueId = function () {
  25169. var result = Scene._uniqueIdCounter;
  25170. Scene._uniqueIdCounter++;
  25171. return result;
  25172. };
  25173. /**
  25174. * Add a mesh to the list of scene's meshes
  25175. * @param newMesh defines the mesh to add
  25176. */
  25177. Scene.prototype.addMesh = function (newMesh) {
  25178. this.meshes.push(newMesh);
  25179. //notify the collision coordinator
  25180. if (this.collisionCoordinator) {
  25181. this.collisionCoordinator.onMeshAdded(newMesh);
  25182. }
  25183. newMesh._resyncLightSources();
  25184. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25185. };
  25186. /**
  25187. * Remove a mesh for the list of scene's meshes
  25188. * @param toRemove defines the mesh to remove
  25189. * @returns the index where the mesh was in the mesh list
  25190. */
  25191. Scene.prototype.removeMesh = function (toRemove) {
  25192. var index = this.meshes.indexOf(toRemove);
  25193. if (index !== -1) {
  25194. // Remove from the scene if mesh found
  25195. this.meshes.splice(index, 1);
  25196. }
  25197. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25198. return index;
  25199. };
  25200. /**
  25201. * Add a transform node to the list of scene's transform nodes
  25202. * @param newTransformNode defines the transform node to add
  25203. */
  25204. Scene.prototype.addTransformNode = function (newTransformNode) {
  25205. this.transformNodes.push(newTransformNode);
  25206. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25207. };
  25208. /**
  25209. * Remove a transform node for the list of scene's transform nodes
  25210. * @param toRemove defines the transform node to remove
  25211. * @returns the index where the transform node was in the transform node list
  25212. */
  25213. Scene.prototype.removeTransformNode = function (toRemove) {
  25214. var index = this.transformNodes.indexOf(toRemove);
  25215. if (index !== -1) {
  25216. // Remove from the scene if found
  25217. this.transformNodes.splice(index, 1);
  25218. }
  25219. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25220. return index;
  25221. };
  25222. /**
  25223. * Remove a skeleton for the list of scene's skeletons
  25224. * @param toRemove defines the skeleton to remove
  25225. * @returns the index where the skeleton was in the skeleton list
  25226. */
  25227. Scene.prototype.removeSkeleton = function (toRemove) {
  25228. var index = this.skeletons.indexOf(toRemove);
  25229. if (index !== -1) {
  25230. // Remove from the scene if found
  25231. this.skeletons.splice(index, 1);
  25232. }
  25233. return index;
  25234. };
  25235. /**
  25236. * Remove a morph target for the list of scene's morph targets
  25237. * @param toRemove defines the morph target to remove
  25238. * @returns the index where the morph target was in the morph target list
  25239. */
  25240. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25241. var index = this.morphTargetManagers.indexOf(toRemove);
  25242. if (index !== -1) {
  25243. // Remove from the scene if found
  25244. this.morphTargetManagers.splice(index, 1);
  25245. }
  25246. return index;
  25247. };
  25248. /**
  25249. * Remove a light for the list of scene's lights
  25250. * @param toRemove defines the light to remove
  25251. * @returns the index where the light was in the light list
  25252. */
  25253. Scene.prototype.removeLight = function (toRemove) {
  25254. var index = this.lights.indexOf(toRemove);
  25255. if (index !== -1) {
  25256. // Remove from meshes
  25257. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25258. var mesh = _a[_i];
  25259. mesh._removeLightSource(toRemove);
  25260. }
  25261. // Remove from the scene if mesh found
  25262. this.lights.splice(index, 1);
  25263. this.sortLightsByPriority();
  25264. }
  25265. this.onLightRemovedObservable.notifyObservers(toRemove);
  25266. return index;
  25267. };
  25268. /**
  25269. * Remove a camera for the list of scene's cameras
  25270. * @param toRemove defines the camera to remove
  25271. * @returns the index where the camera was in the camera list
  25272. */
  25273. Scene.prototype.removeCamera = function (toRemove) {
  25274. var index = this.cameras.indexOf(toRemove);
  25275. if (index !== -1) {
  25276. // Remove from the scene if mesh found
  25277. this.cameras.splice(index, 1);
  25278. }
  25279. // Remove from activeCameras
  25280. var index2 = this.activeCameras.indexOf(toRemove);
  25281. if (index2 !== -1) {
  25282. // Remove from the scene if mesh found
  25283. this.activeCameras.splice(index2, 1);
  25284. }
  25285. // Reset the activeCamera
  25286. if (this.activeCamera === toRemove) {
  25287. if (this.cameras.length > 0) {
  25288. this.activeCamera = this.cameras[0];
  25289. }
  25290. else {
  25291. this.activeCamera = null;
  25292. }
  25293. }
  25294. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25295. return index;
  25296. };
  25297. /**
  25298. * Remove a particle system for the list of scene's particle systems
  25299. * @param toRemove defines the particle system to remove
  25300. * @returns the index where the particle system was in the particle system list
  25301. */
  25302. Scene.prototype.removeParticleSystem = function (toRemove) {
  25303. var index = this.particleSystems.indexOf(toRemove);
  25304. if (index !== -1) {
  25305. this.particleSystems.splice(index, 1);
  25306. }
  25307. return index;
  25308. };
  25309. /**
  25310. * Remove a animation for the list of scene's animations
  25311. * @param toRemove defines the animation to remove
  25312. * @returns the index where the animation was in the animation list
  25313. */
  25314. Scene.prototype.removeAnimation = function (toRemove) {
  25315. var index = this.animations.indexOf(toRemove);
  25316. if (index !== -1) {
  25317. this.animations.splice(index, 1);
  25318. }
  25319. return index;
  25320. };
  25321. /**
  25322. * Removes the given animation group from this scene.
  25323. * @param toRemove The animation group to remove
  25324. * @returns The index of the removed animation group
  25325. */
  25326. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25327. var index = this.animationGroups.indexOf(toRemove);
  25328. if (index !== -1) {
  25329. this.animationGroups.splice(index, 1);
  25330. }
  25331. return index;
  25332. };
  25333. /**
  25334. * Removes the given multi-material from this scene.
  25335. * @param toRemove The multi-material to remove
  25336. * @returns The index of the removed multi-material
  25337. */
  25338. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25339. var index = this.multiMaterials.indexOf(toRemove);
  25340. if (index !== -1) {
  25341. this.multiMaterials.splice(index, 1);
  25342. }
  25343. return index;
  25344. };
  25345. /**
  25346. * Removes the given material from this scene.
  25347. * @param toRemove The material to remove
  25348. * @returns The index of the removed material
  25349. */
  25350. Scene.prototype.removeMaterial = function (toRemove) {
  25351. var index = this.materials.indexOf(toRemove);
  25352. if (index !== -1) {
  25353. this.materials.splice(index, 1);
  25354. }
  25355. return index;
  25356. };
  25357. /**
  25358. * Removes the given lens flare system from this scene.
  25359. * @param toRemove The lens flare system to remove
  25360. * @returns The index of the removed lens flare system
  25361. */
  25362. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25363. var index = this.lensFlareSystems.indexOf(toRemove);
  25364. if (index !== -1) {
  25365. this.lensFlareSystems.splice(index, 1);
  25366. }
  25367. return index;
  25368. };
  25369. /**
  25370. * Removes the given action manager from this scene.
  25371. * @param toRemove The action manager to remove
  25372. * @returns The index of the removed action manager
  25373. */
  25374. Scene.prototype.removeActionManager = function (toRemove) {
  25375. var index = this._actionManagers.indexOf(toRemove);
  25376. if (index !== -1) {
  25377. this._actionManagers.splice(index, 1);
  25378. }
  25379. return index;
  25380. };
  25381. /**
  25382. * Removes the given texture from this scene.
  25383. * @param toRemove The texture to remove
  25384. * @returns The index of the removed texture
  25385. */
  25386. Scene.prototype.removeTexture = function (toRemove) {
  25387. var index = this.textures.indexOf(toRemove);
  25388. if (index !== -1) {
  25389. this.textures.splice(index, 1);
  25390. }
  25391. return index;
  25392. };
  25393. /**
  25394. * Adds the given light to this scene
  25395. * @param newLight The light to add
  25396. */
  25397. Scene.prototype.addLight = function (newLight) {
  25398. this.lights.push(newLight);
  25399. this.sortLightsByPriority();
  25400. // Add light to all meshes (To support if the light is removed and then readded)
  25401. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25402. var mesh = _a[_i];
  25403. if (mesh._lightSources.indexOf(newLight) === -1) {
  25404. mesh._lightSources.push(newLight);
  25405. mesh._resyncLightSources();
  25406. }
  25407. }
  25408. this.onNewLightAddedObservable.notifyObservers(newLight);
  25409. };
  25410. /**
  25411. * Sorts the list list based on light priorities
  25412. */
  25413. Scene.prototype.sortLightsByPriority = function () {
  25414. if (this.requireLightSorting) {
  25415. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25416. }
  25417. };
  25418. /**
  25419. * Adds the given camera to this scene
  25420. * @param newCamera The camera to add
  25421. */
  25422. Scene.prototype.addCamera = function (newCamera) {
  25423. this.cameras.push(newCamera);
  25424. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25425. };
  25426. /**
  25427. * Adds the given skeleton to this scene
  25428. * @param newSkeleton The skeleton to add
  25429. */
  25430. Scene.prototype.addSkeleton = function (newSkeleton) {
  25431. this.skeletons.push(newSkeleton);
  25432. };
  25433. /**
  25434. * Adds the given particle system to this scene
  25435. * @param newParticleSystem The particle system to add
  25436. */
  25437. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25438. this.particleSystems.push(newParticleSystem);
  25439. };
  25440. /**
  25441. * Adds the given animation to this scene
  25442. * @param newAnimation The animation to add
  25443. */
  25444. Scene.prototype.addAnimation = function (newAnimation) {
  25445. this.animations.push(newAnimation);
  25446. };
  25447. /**
  25448. * Adds the given animation group to this scene.
  25449. * @param newAnimationGroup The animation group to add
  25450. */
  25451. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25452. this.animationGroups.push(newAnimationGroup);
  25453. };
  25454. /**
  25455. * Adds the given multi-material to this scene
  25456. * @param newMultiMaterial The multi-material to add
  25457. */
  25458. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25459. this.multiMaterials.push(newMultiMaterial);
  25460. };
  25461. /**
  25462. * Adds the given material to this scene
  25463. * @param newMaterial The material to add
  25464. */
  25465. Scene.prototype.addMaterial = function (newMaterial) {
  25466. this.materials.push(newMaterial);
  25467. };
  25468. /**
  25469. * Adds the given morph target to this scene
  25470. * @param newMorphTargetManager The morph target to add
  25471. */
  25472. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25473. this.morphTargetManagers.push(newMorphTargetManager);
  25474. };
  25475. /**
  25476. * Adds the given geometry to this scene
  25477. * @param newGeometry The geometry to add
  25478. */
  25479. Scene.prototype.addGeometry = function (newGeometry) {
  25480. this._geometries.push(newGeometry);
  25481. };
  25482. /**
  25483. * Adds the given lens flare system to this scene
  25484. * @param newLensFlareSystem The lens flare system to add
  25485. */
  25486. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25487. this.lensFlareSystems.push(newLensFlareSystem);
  25488. };
  25489. /**
  25490. * Adds the given action manager to this scene
  25491. * @param newActionManager The action manager to add
  25492. */
  25493. Scene.prototype.addActionManager = function (newActionManager) {
  25494. this._actionManagers.push(newActionManager);
  25495. };
  25496. /**
  25497. * Adds the given texture to this scene.
  25498. * @param newTexture The texture to add
  25499. */
  25500. Scene.prototype.addTexture = function (newTexture) {
  25501. this.textures.push(newTexture);
  25502. };
  25503. /**
  25504. * Switch active camera
  25505. * @param newCamera defines the new active camera
  25506. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25507. */
  25508. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25509. if (attachControl === void 0) { attachControl = true; }
  25510. var canvas = this._engine.getRenderingCanvas();
  25511. if (!canvas) {
  25512. return;
  25513. }
  25514. if (this.activeCamera) {
  25515. this.activeCamera.detachControl(canvas);
  25516. }
  25517. this.activeCamera = newCamera;
  25518. if (attachControl) {
  25519. newCamera.attachControl(canvas);
  25520. }
  25521. };
  25522. /**
  25523. * sets the active camera of the scene using its ID
  25524. * @param id defines the camera's ID
  25525. * @return the new active camera or null if none found.
  25526. */
  25527. Scene.prototype.setActiveCameraByID = function (id) {
  25528. var camera = this.getCameraByID(id);
  25529. if (camera) {
  25530. this.activeCamera = camera;
  25531. return camera;
  25532. }
  25533. return null;
  25534. };
  25535. /**
  25536. * sets the active camera of the scene using its name
  25537. * @param name defines the camera's name
  25538. * @returns the new active camera or null if none found.
  25539. */
  25540. Scene.prototype.setActiveCameraByName = function (name) {
  25541. var camera = this.getCameraByName(name);
  25542. if (camera) {
  25543. this.activeCamera = camera;
  25544. return camera;
  25545. }
  25546. return null;
  25547. };
  25548. /**
  25549. * get an animation group using its name
  25550. * @param name defines the material's name
  25551. * @return the animation group or null if none found.
  25552. */
  25553. Scene.prototype.getAnimationGroupByName = function (name) {
  25554. for (var index = 0; index < this.animationGroups.length; index++) {
  25555. if (this.animationGroups[index].name === name) {
  25556. return this.animationGroups[index];
  25557. }
  25558. }
  25559. return null;
  25560. };
  25561. /**
  25562. * get a material using its id
  25563. * @param id defines the material's ID
  25564. * @return the material or null if none found.
  25565. */
  25566. Scene.prototype.getMaterialByID = function (id) {
  25567. for (var index = 0; index < this.materials.length; index++) {
  25568. if (this.materials[index].id === id) {
  25569. return this.materials[index];
  25570. }
  25571. }
  25572. return null;
  25573. };
  25574. /**
  25575. * Gets a material using its name
  25576. * @param name defines the material's name
  25577. * @return the material or null if none found.
  25578. */
  25579. Scene.prototype.getMaterialByName = function (name) {
  25580. for (var index = 0; index < this.materials.length; index++) {
  25581. if (this.materials[index].name === name) {
  25582. return this.materials[index];
  25583. }
  25584. }
  25585. return null;
  25586. };
  25587. /**
  25588. * Gets a lens flare system using its name
  25589. * @param name defines the name to look for
  25590. * @returns the lens flare system or null if not found
  25591. */
  25592. Scene.prototype.getLensFlareSystemByName = function (name) {
  25593. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25594. if (this.lensFlareSystems[index].name === name) {
  25595. return this.lensFlareSystems[index];
  25596. }
  25597. }
  25598. return null;
  25599. };
  25600. /**
  25601. * Gets a lens flare system using its id
  25602. * @param id defines the id to look for
  25603. * @returns the lens flare system or null if not found
  25604. */
  25605. Scene.prototype.getLensFlareSystemByID = function (id) {
  25606. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25607. if (this.lensFlareSystems[index].id === id) {
  25608. return this.lensFlareSystems[index];
  25609. }
  25610. }
  25611. return null;
  25612. };
  25613. /**
  25614. * Gets a camera using its id
  25615. * @param id defines the id to look for
  25616. * @returns the camera or null if not found
  25617. */
  25618. Scene.prototype.getCameraByID = function (id) {
  25619. for (var index = 0; index < this.cameras.length; index++) {
  25620. if (this.cameras[index].id === id) {
  25621. return this.cameras[index];
  25622. }
  25623. }
  25624. return null;
  25625. };
  25626. /**
  25627. * Gets a camera using its unique id
  25628. * @param uniqueId defines the unique id to look for
  25629. * @returns the camera or null if not found
  25630. */
  25631. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25632. for (var index = 0; index < this.cameras.length; index++) {
  25633. if (this.cameras[index].uniqueId === uniqueId) {
  25634. return this.cameras[index];
  25635. }
  25636. }
  25637. return null;
  25638. };
  25639. /**
  25640. * Gets a camera using its name
  25641. * @param name defines the camera's name
  25642. * @return the camera or null if none found.
  25643. */
  25644. Scene.prototype.getCameraByName = function (name) {
  25645. for (var index = 0; index < this.cameras.length; index++) {
  25646. if (this.cameras[index].name === name) {
  25647. return this.cameras[index];
  25648. }
  25649. }
  25650. return null;
  25651. };
  25652. /**
  25653. * Gets a bone using its id
  25654. * @param id defines the bone's id
  25655. * @return the bone or null if not found
  25656. */
  25657. Scene.prototype.getBoneByID = function (id) {
  25658. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25659. var skeleton = this.skeletons[skeletonIndex];
  25660. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25661. if (skeleton.bones[boneIndex].id === id) {
  25662. return skeleton.bones[boneIndex];
  25663. }
  25664. }
  25665. }
  25666. return null;
  25667. };
  25668. /**
  25669. * Gets a bone using its id
  25670. * @param name defines the bone's name
  25671. * @return the bone or null if not found
  25672. */
  25673. Scene.prototype.getBoneByName = function (name) {
  25674. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25675. var skeleton = this.skeletons[skeletonIndex];
  25676. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25677. if (skeleton.bones[boneIndex].name === name) {
  25678. return skeleton.bones[boneIndex];
  25679. }
  25680. }
  25681. }
  25682. return null;
  25683. };
  25684. /**
  25685. * Gets a light node using its name
  25686. * @param name defines the the light's name
  25687. * @return the light or null if none found.
  25688. */
  25689. Scene.prototype.getLightByName = function (name) {
  25690. for (var index = 0; index < this.lights.length; index++) {
  25691. if (this.lights[index].name === name) {
  25692. return this.lights[index];
  25693. }
  25694. }
  25695. return null;
  25696. };
  25697. /**
  25698. * Gets a light node using its id
  25699. * @param id defines the light's id
  25700. * @return the light or null if none found.
  25701. */
  25702. Scene.prototype.getLightByID = function (id) {
  25703. for (var index = 0; index < this.lights.length; index++) {
  25704. if (this.lights[index].id === id) {
  25705. return this.lights[index];
  25706. }
  25707. }
  25708. return null;
  25709. };
  25710. /**
  25711. * Gets a light node using its scene-generated unique ID
  25712. * @param uniqueId defines the light's unique id
  25713. * @return the light or null if none found.
  25714. */
  25715. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  25716. for (var index = 0; index < this.lights.length; index++) {
  25717. if (this.lights[index].uniqueId === uniqueId) {
  25718. return this.lights[index];
  25719. }
  25720. }
  25721. return null;
  25722. };
  25723. /**
  25724. * Gets a particle system by id
  25725. * @param id defines the particle system id
  25726. * @return the corresponding system or null if none found
  25727. */
  25728. Scene.prototype.getParticleSystemByID = function (id) {
  25729. for (var index = 0; index < this.particleSystems.length; index++) {
  25730. if (this.particleSystems[index].id === id) {
  25731. return this.particleSystems[index];
  25732. }
  25733. }
  25734. return null;
  25735. };
  25736. /**
  25737. * Gets a geometry using its ID
  25738. * @param id defines the geometry's id
  25739. * @return the geometry or null if none found.
  25740. */
  25741. Scene.prototype.getGeometryByID = function (id) {
  25742. for (var index = 0; index < this._geometries.length; index++) {
  25743. if (this._geometries[index].id === id) {
  25744. return this._geometries[index];
  25745. }
  25746. }
  25747. return null;
  25748. };
  25749. /**
  25750. * Add a new geometry to this scene
  25751. * @param geometry defines the geometry to be added to the scene.
  25752. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  25753. * @return a boolean defining if the geometry was added or not
  25754. */
  25755. Scene.prototype.pushGeometry = function (geometry, force) {
  25756. if (!force && this.getGeometryByID(geometry.id)) {
  25757. return false;
  25758. }
  25759. this._geometries.push(geometry);
  25760. //notify the collision coordinator
  25761. if (this.collisionCoordinator) {
  25762. this.collisionCoordinator.onGeometryAdded(geometry);
  25763. }
  25764. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  25765. return true;
  25766. };
  25767. /**
  25768. * Removes an existing geometry
  25769. * @param geometry defines the geometry to be removed from the scene
  25770. * @return a boolean defining if the geometry was removed or not
  25771. */
  25772. Scene.prototype.removeGeometry = function (geometry) {
  25773. var index = this._geometries.indexOf(geometry);
  25774. if (index > -1) {
  25775. this._geometries.splice(index, 1);
  25776. //notify the collision coordinator
  25777. if (this.collisionCoordinator) {
  25778. this.collisionCoordinator.onGeometryDeleted(geometry);
  25779. }
  25780. this.onGeometryRemovedObservable.notifyObservers(geometry);
  25781. return true;
  25782. }
  25783. return false;
  25784. };
  25785. /**
  25786. * Gets the list of geometries attached to the scene
  25787. * @returns an array of Geometry
  25788. */
  25789. Scene.prototype.getGeometries = function () {
  25790. return this._geometries;
  25791. };
  25792. /**
  25793. * Gets the first added mesh found of a given ID
  25794. * @param id defines the id to search for
  25795. * @return the mesh found or null if not found at all
  25796. */
  25797. Scene.prototype.getMeshByID = function (id) {
  25798. for (var index = 0; index < this.meshes.length; index++) {
  25799. if (this.meshes[index].id === id) {
  25800. return this.meshes[index];
  25801. }
  25802. }
  25803. return null;
  25804. };
  25805. /**
  25806. * Gets a list of meshes using their id
  25807. * @param id defines the id to search for
  25808. * @returns a list of meshes
  25809. */
  25810. Scene.prototype.getMeshesByID = function (id) {
  25811. return this.meshes.filter(function (m) {
  25812. return m.id === id;
  25813. });
  25814. };
  25815. /**
  25816. * Gets the first added transform node found of a given ID
  25817. * @param id defines the id to search for
  25818. * @return the found transform node or null if not found at all.
  25819. */
  25820. Scene.prototype.getTransformNodeByID = function (id) {
  25821. for (var index = 0; index < this.transformNodes.length; index++) {
  25822. if (this.transformNodes[index].id === id) {
  25823. return this.transformNodes[index];
  25824. }
  25825. }
  25826. return null;
  25827. };
  25828. /**
  25829. * Gets a list of transform nodes using their id
  25830. * @param id defines the id to search for
  25831. * @returns a list of transform nodes
  25832. */
  25833. Scene.prototype.getTransformNodesByID = function (id) {
  25834. return this.transformNodes.filter(function (m) {
  25835. return m.id === id;
  25836. });
  25837. };
  25838. /**
  25839. * Gets a mesh with its auto-generated unique id
  25840. * @param uniqueId defines the unique id to search for
  25841. * @return the found mesh or null if not found at all.
  25842. */
  25843. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  25844. for (var index = 0; index < this.meshes.length; index++) {
  25845. if (this.meshes[index].uniqueId === uniqueId) {
  25846. return this.meshes[index];
  25847. }
  25848. }
  25849. return null;
  25850. };
  25851. /**
  25852. * Gets a the last added mesh using a given id
  25853. * @param id defines the id to search for
  25854. * @return the found mesh or null if not found at all.
  25855. */
  25856. Scene.prototype.getLastMeshByID = function (id) {
  25857. for (var index = this.meshes.length - 1; index >= 0; index--) {
  25858. if (this.meshes[index].id === id) {
  25859. return this.meshes[index];
  25860. }
  25861. }
  25862. return null;
  25863. };
  25864. /**
  25865. * Gets a the last added node (Mesh, Camera, Light) using a given id
  25866. * @param id defines the id to search for
  25867. * @return the found node or null if not found at all
  25868. */
  25869. Scene.prototype.getLastEntryByID = function (id) {
  25870. var index;
  25871. for (index = this.meshes.length - 1; index >= 0; index--) {
  25872. if (this.meshes[index].id === id) {
  25873. return this.meshes[index];
  25874. }
  25875. }
  25876. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  25877. if (this.transformNodes[index].id === id) {
  25878. return this.transformNodes[index];
  25879. }
  25880. }
  25881. for (index = this.cameras.length - 1; index >= 0; index--) {
  25882. if (this.cameras[index].id === id) {
  25883. return this.cameras[index];
  25884. }
  25885. }
  25886. for (index = this.lights.length - 1; index >= 0; index--) {
  25887. if (this.lights[index].id === id) {
  25888. return this.lights[index];
  25889. }
  25890. }
  25891. return null;
  25892. };
  25893. /**
  25894. * Gets a node (Mesh, Camera, Light) using a given id
  25895. * @param id defines the id to search for
  25896. * @return the found node or null if not found at all
  25897. */
  25898. Scene.prototype.getNodeByID = function (id) {
  25899. var mesh = this.getMeshByID(id);
  25900. if (mesh) {
  25901. return mesh;
  25902. }
  25903. var light = this.getLightByID(id);
  25904. if (light) {
  25905. return light;
  25906. }
  25907. var camera = this.getCameraByID(id);
  25908. if (camera) {
  25909. return camera;
  25910. }
  25911. var bone = this.getBoneByID(id);
  25912. return bone;
  25913. };
  25914. /**
  25915. * Gets a node (Mesh, Camera, Light) using a given name
  25916. * @param name defines the name to search for
  25917. * @return the found node or null if not found at all.
  25918. */
  25919. Scene.prototype.getNodeByName = function (name) {
  25920. var mesh = this.getMeshByName(name);
  25921. if (mesh) {
  25922. return mesh;
  25923. }
  25924. var light = this.getLightByName(name);
  25925. if (light) {
  25926. return light;
  25927. }
  25928. var camera = this.getCameraByName(name);
  25929. if (camera) {
  25930. return camera;
  25931. }
  25932. var bone = this.getBoneByName(name);
  25933. return bone;
  25934. };
  25935. /**
  25936. * Gets a mesh using a given name
  25937. * @param name defines the name to search for
  25938. * @return the found mesh or null if not found at all.
  25939. */
  25940. Scene.prototype.getMeshByName = function (name) {
  25941. for (var index = 0; index < this.meshes.length; index++) {
  25942. if (this.meshes[index].name === name) {
  25943. return this.meshes[index];
  25944. }
  25945. }
  25946. return null;
  25947. };
  25948. /**
  25949. * Gets a transform node using a given name
  25950. * @param name defines the name to search for
  25951. * @return the found transform node or null if not found at all.
  25952. */
  25953. Scene.prototype.getTransformNodeByName = function (name) {
  25954. for (var index = 0; index < this.transformNodes.length; index++) {
  25955. if (this.transformNodes[index].name === name) {
  25956. return this.transformNodes[index];
  25957. }
  25958. }
  25959. return null;
  25960. };
  25961. /**
  25962. * Gets a sound using a given name
  25963. * @param name defines the name to search for
  25964. * @return the found sound or null if not found at all.
  25965. */
  25966. Scene.prototype.getSoundByName = function (name) {
  25967. var index;
  25968. if (BABYLON.AudioEngine) {
  25969. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  25970. if (this.mainSoundTrack.soundCollection[index].name === name) {
  25971. return this.mainSoundTrack.soundCollection[index];
  25972. }
  25973. }
  25974. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  25975. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  25976. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  25977. return this.soundTracks[sdIndex].soundCollection[index];
  25978. }
  25979. }
  25980. }
  25981. }
  25982. return null;
  25983. };
  25984. /**
  25985. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  25986. * @param id defines the id to search for
  25987. * @return the found skeleton or null if not found at all.
  25988. */
  25989. Scene.prototype.getLastSkeletonByID = function (id) {
  25990. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  25991. if (this.skeletons[index].id === id) {
  25992. return this.skeletons[index];
  25993. }
  25994. }
  25995. return null;
  25996. };
  25997. /**
  25998. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  25999. * @param id defines the id to search for
  26000. * @return the found skeleton or null if not found at all.
  26001. */
  26002. Scene.prototype.getSkeletonById = function (id) {
  26003. for (var index = 0; index < this.skeletons.length; index++) {
  26004. if (this.skeletons[index].id === id) {
  26005. return this.skeletons[index];
  26006. }
  26007. }
  26008. return null;
  26009. };
  26010. /**
  26011. * Gets a skeleton using a given name
  26012. * @param name defines the name to search for
  26013. * @return the found skeleton or null if not found at all.
  26014. */
  26015. Scene.prototype.getSkeletonByName = function (name) {
  26016. for (var index = 0; index < this.skeletons.length; index++) {
  26017. if (this.skeletons[index].name === name) {
  26018. return this.skeletons[index];
  26019. }
  26020. }
  26021. return null;
  26022. };
  26023. /**
  26024. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26025. * @param id defines the id to search for
  26026. * @return the found morph target manager or null if not found at all.
  26027. */
  26028. Scene.prototype.getMorphTargetManagerById = function (id) {
  26029. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26030. if (this.morphTargetManagers[index].uniqueId === id) {
  26031. return this.morphTargetManagers[index];
  26032. }
  26033. }
  26034. return null;
  26035. };
  26036. /**
  26037. * Gets a boolean indicating if the given mesh is active
  26038. * @param mesh defines the mesh to look for
  26039. * @returns true if the mesh is in the active list
  26040. */
  26041. Scene.prototype.isActiveMesh = function (mesh) {
  26042. return (this._activeMeshes.indexOf(mesh) !== -1);
  26043. };
  26044. /**
  26045. * Return a the first highlight layer of the scene with a given name.
  26046. * @param name The name of the highlight layer to look for.
  26047. * @return The highlight layer if found otherwise null.
  26048. */
  26049. Scene.prototype.getHighlightLayerByName = function (name) {
  26050. for (var index = 0; index < this.effectLayers.length; index++) {
  26051. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26052. return this.effectLayers[index];
  26053. }
  26054. }
  26055. return null;
  26056. };
  26057. /**
  26058. * Return a the first highlight layer of the scene with a given name.
  26059. * @param name The name of the highlight layer to look for.
  26060. * @return The highlight layer if found otherwise null.
  26061. */
  26062. Scene.prototype.getGlowLayerByName = function (name) {
  26063. for (var index = 0; index < this.effectLayers.length; index++) {
  26064. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26065. return this.effectLayers[index];
  26066. }
  26067. }
  26068. return null;
  26069. };
  26070. Object.defineProperty(Scene.prototype, "uid", {
  26071. /**
  26072. * Return a unique id as a string which can serve as an identifier for the scene
  26073. */
  26074. get: function () {
  26075. if (!this._uid) {
  26076. this._uid = BABYLON.Tools.RandomId();
  26077. }
  26078. return this._uid;
  26079. },
  26080. enumerable: true,
  26081. configurable: true
  26082. });
  26083. /**
  26084. * Add an externaly attached data from its key.
  26085. * This method call will fail and return false, if such key already exists.
  26086. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26087. * @param key the unique key that identifies the data
  26088. * @param data the data object to associate to the key for this Engine instance
  26089. * @return true if no such key were already present and the data was added successfully, false otherwise
  26090. */
  26091. Scene.prototype.addExternalData = function (key, data) {
  26092. if (!this._externalData) {
  26093. this._externalData = new BABYLON.StringDictionary();
  26094. }
  26095. return this._externalData.add(key, data);
  26096. };
  26097. /**
  26098. * Get an externaly attached data from its key
  26099. * @param key the unique key that identifies the data
  26100. * @return the associated data, if present (can be null), or undefined if not present
  26101. */
  26102. Scene.prototype.getExternalData = function (key) {
  26103. if (!this._externalData) {
  26104. return null;
  26105. }
  26106. return this._externalData.get(key);
  26107. };
  26108. /**
  26109. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26110. * @param key the unique key that identifies the data
  26111. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26112. * @return the associated data, can be null if the factory returned null.
  26113. */
  26114. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26115. if (!this._externalData) {
  26116. this._externalData = new BABYLON.StringDictionary();
  26117. }
  26118. return this._externalData.getOrAddWithFactory(key, factory);
  26119. };
  26120. /**
  26121. * Remove an externaly attached data from the Engine instance
  26122. * @param key the unique key that identifies the data
  26123. * @return true if the data was successfully removed, false if it doesn't exist
  26124. */
  26125. Scene.prototype.removeExternalData = function (key) {
  26126. return this._externalData.remove(key);
  26127. };
  26128. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26129. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26130. if (mesh.showSubMeshesBoundingBox) {
  26131. var boundingInfo = subMesh.getBoundingInfo();
  26132. if (boundingInfo !== null && boundingInfo !== undefined) {
  26133. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26134. }
  26135. }
  26136. var material = subMesh.getMaterial();
  26137. if (material !== null && material !== undefined) {
  26138. // Render targets
  26139. if (material.getRenderTargetTextures !== undefined) {
  26140. if (this._processedMaterials.indexOf(material) === -1) {
  26141. this._processedMaterials.push(material);
  26142. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26143. }
  26144. }
  26145. // Dispatch
  26146. this._activeIndices.addCount(subMesh.indexCount, false);
  26147. this._renderingManager.dispatch(subMesh, mesh, material);
  26148. }
  26149. }
  26150. };
  26151. /**
  26152. * Clear the processed materials smart array preventing retention point in material dispose.
  26153. */
  26154. Scene.prototype.freeProcessedMaterials = function () {
  26155. this._processedMaterials.dispose();
  26156. };
  26157. /**
  26158. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26159. */
  26160. Scene.prototype.freeActiveMeshes = function () {
  26161. this._activeMeshes.dispose();
  26162. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26163. this.activeCamera._activeMeshes.dispose();
  26164. }
  26165. if (this.activeCameras) {
  26166. for (var i = 0; i < this.activeCameras.length; i++) {
  26167. var activeCamera = this.activeCameras[i];
  26168. if (activeCamera && activeCamera._activeMeshes) {
  26169. activeCamera._activeMeshes.dispose();
  26170. }
  26171. }
  26172. }
  26173. };
  26174. /**
  26175. * Clear the info related to rendering groups preventing retention points during dispose.
  26176. */
  26177. Scene.prototype.freeRenderingGroups = function () {
  26178. if (this._renderingManager) {
  26179. this._renderingManager.freeRenderingGroups();
  26180. }
  26181. if (this.textures) {
  26182. for (var i = 0; i < this.textures.length; i++) {
  26183. var texture = this.textures[i];
  26184. if (texture && texture.renderList) {
  26185. texture.freeRenderingGroups();
  26186. }
  26187. }
  26188. }
  26189. };
  26190. /** @ignore */
  26191. Scene.prototype._isInIntermediateRendering = function () {
  26192. return this._intermediateRendering;
  26193. };
  26194. /**
  26195. * Defines the current active mesh candidate provider
  26196. * @param provider defines the provider to use
  26197. */
  26198. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26199. this._activeMeshCandidateProvider = provider;
  26200. };
  26201. /**
  26202. * Gets the current active mesh candidate provider
  26203. * @returns the current active mesh candidate provider
  26204. */
  26205. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26206. return this._activeMeshCandidateProvider;
  26207. };
  26208. /**
  26209. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26210. * @returns the current scene
  26211. */
  26212. Scene.prototype.freezeActiveMeshes = function () {
  26213. if (!this.activeCamera) {
  26214. return this;
  26215. }
  26216. if (!this._frustumPlanes) {
  26217. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26218. }
  26219. this._evaluateActiveMeshes();
  26220. this._activeMeshesFrozen = true;
  26221. return this;
  26222. };
  26223. /**
  26224. * Use this function to restart evaluating active meshes on every frame
  26225. * @returns the current scene
  26226. */
  26227. Scene.prototype.unfreezeActiveMeshes = function () {
  26228. this._activeMeshesFrozen = false;
  26229. return this;
  26230. };
  26231. Scene.prototype._evaluateActiveMeshes = function () {
  26232. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26233. return;
  26234. }
  26235. if (!this.activeCamera) {
  26236. return;
  26237. }
  26238. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26239. this.activeCamera._activeMeshes.reset();
  26240. this._activeMeshes.reset();
  26241. this._renderingManager.reset();
  26242. this._processedMaterials.reset();
  26243. this._activeParticleSystems.reset();
  26244. this._activeSkeletons.reset();
  26245. this._softwareSkinnedMeshes.reset();
  26246. if (this._boundingBoxRenderer) {
  26247. this._boundingBoxRenderer.reset();
  26248. }
  26249. // Meshes
  26250. var meshes;
  26251. var len;
  26252. var checkIsEnabled = true;
  26253. // Determine mesh candidates
  26254. if (this._activeMeshCandidateProvider !== undefined) {
  26255. // Use _activeMeshCandidateProvider
  26256. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26257. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26258. if (meshes !== undefined) {
  26259. len = meshes.length;
  26260. }
  26261. else {
  26262. len = 0;
  26263. }
  26264. }
  26265. else if (this._selectionOctree !== undefined) {
  26266. // Octree
  26267. var selection = this._selectionOctree.select(this._frustumPlanes);
  26268. meshes = selection.data;
  26269. len = selection.length;
  26270. }
  26271. else {
  26272. // Full scene traversal
  26273. len = this.meshes.length;
  26274. meshes = this.meshes;
  26275. }
  26276. // Check each mesh
  26277. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26278. mesh = meshes[meshIndex];
  26279. if (mesh.isBlocked) {
  26280. continue;
  26281. }
  26282. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26283. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26284. continue;
  26285. }
  26286. mesh.computeWorldMatrix();
  26287. // Intersections
  26288. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26289. this._meshesForIntersections.pushNoDuplicate(mesh);
  26290. }
  26291. // Switch to current LOD
  26292. meshLOD = mesh.getLOD(this.activeCamera);
  26293. if (meshLOD === undefined || meshLOD === null) {
  26294. continue;
  26295. }
  26296. mesh._preActivate();
  26297. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26298. this._activeMeshes.push(mesh);
  26299. this.activeCamera._activeMeshes.push(mesh);
  26300. mesh._activate(this._renderId);
  26301. if (meshLOD !== mesh) {
  26302. meshLOD._activate(this._renderId);
  26303. }
  26304. this._activeMesh(mesh, meshLOD);
  26305. }
  26306. }
  26307. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26308. // Particle systems
  26309. if (this.particlesEnabled) {
  26310. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26311. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26312. var particleSystem = this.particleSystems[particleIndex];
  26313. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26314. continue;
  26315. }
  26316. var emitter = particleSystem.emitter;
  26317. if (!emitter.position || emitter.isEnabled()) {
  26318. this._activeParticleSystems.push(particleSystem);
  26319. particleSystem.animate();
  26320. this._renderingManager.dispatchParticles(particleSystem);
  26321. }
  26322. }
  26323. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26324. }
  26325. };
  26326. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26327. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26328. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26329. mesh.skeleton.prepare();
  26330. }
  26331. if (!mesh.computeBonesUsingShaders) {
  26332. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26333. }
  26334. }
  26335. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26336. var boundingInfo = sourceMesh.getBoundingInfo();
  26337. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26338. }
  26339. if (mesh !== undefined && mesh !== null
  26340. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26341. // Submeshes Octrees
  26342. var len;
  26343. var subMeshes;
  26344. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26345. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26346. len = intersections.length;
  26347. subMeshes = intersections.data;
  26348. }
  26349. else {
  26350. subMeshes = mesh.subMeshes;
  26351. len = subMeshes.length;
  26352. }
  26353. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26354. subMesh = subMeshes[subIndex];
  26355. this._evaluateSubMesh(subMesh, mesh);
  26356. }
  26357. }
  26358. };
  26359. /**
  26360. * Update the transform matrix to update from the current active camera
  26361. * @param force defines a boolean used to force the update even if cache is up to date
  26362. */
  26363. Scene.prototype.updateTransformMatrix = function (force) {
  26364. if (!this.activeCamera) {
  26365. return;
  26366. }
  26367. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26368. };
  26369. /**
  26370. * 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)
  26371. * @param alternateCamera defines the camera to use
  26372. */
  26373. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26374. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26375. };
  26376. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26377. if (camera && camera._skipRendering) {
  26378. return;
  26379. }
  26380. var engine = this._engine;
  26381. this.activeCamera = camera;
  26382. if (!this.activeCamera)
  26383. throw new Error("Active camera not set");
  26384. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26385. // Viewport
  26386. engine.setViewport(this.activeCamera.viewport);
  26387. // Camera
  26388. this.resetCachedMaterial();
  26389. this._renderId++;
  26390. this.updateTransformMatrix();
  26391. if (camera._alternateCamera) {
  26392. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26393. this._alternateRendering = true;
  26394. }
  26395. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26396. // Meshes
  26397. this._evaluateActiveMeshes();
  26398. // Software skinning
  26399. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26400. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26401. mesh.applySkeleton(mesh.skeleton);
  26402. }
  26403. // Render targets
  26404. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26405. var needsRestoreFrameBuffer = false;
  26406. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26407. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26408. }
  26409. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26410. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26411. }
  26412. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26413. this._intermediateRendering = true;
  26414. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26415. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26416. var renderTarget = this._renderTargets.data[renderIndex];
  26417. if (renderTarget._shouldRender()) {
  26418. this._renderId++;
  26419. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26420. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26421. }
  26422. }
  26423. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26424. this._intermediateRendering = false;
  26425. this._renderId++;
  26426. needsRestoreFrameBuffer = true; // Restore back buffer
  26427. }
  26428. // Render EffecttLayer Texture
  26429. var stencilState = this._engine.getStencilBuffer();
  26430. var renderEffects = false;
  26431. var needStencil = false;
  26432. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26433. this._intermediateRendering = true;
  26434. for (var i = 0; i < this.effectLayers.length; i++) {
  26435. var effectLayer = this.effectLayers[i];
  26436. if (effectLayer.shouldRender() &&
  26437. (!effectLayer.camera ||
  26438. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26439. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26440. renderEffects = true;
  26441. needStencil = needStencil || effectLayer.needStencil();
  26442. var renderTarget = effectLayer._mainTexture;
  26443. if (renderTarget._shouldRender()) {
  26444. this._renderId++;
  26445. renderTarget.render(false, false);
  26446. needsRestoreFrameBuffer = true;
  26447. }
  26448. }
  26449. }
  26450. this._intermediateRendering = false;
  26451. this._renderId++;
  26452. }
  26453. if (needsRestoreFrameBuffer) {
  26454. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26455. }
  26456. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26457. // Prepare Frame
  26458. this.postProcessManager._prepareFrame();
  26459. // Backgrounds
  26460. var layerIndex;
  26461. var layer;
  26462. if (this.layers.length) {
  26463. engine.setDepthBuffer(false);
  26464. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26465. layer = this.layers[layerIndex];
  26466. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26467. layer.render();
  26468. }
  26469. }
  26470. engine.setDepthBuffer(true);
  26471. }
  26472. // Activate effect Layer stencil
  26473. if (needStencil) {
  26474. this._engine.setStencilBuffer(true);
  26475. }
  26476. // Render
  26477. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26478. this._renderingManager.render(null, null, true, true);
  26479. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26480. // Restore effect Layer stencil
  26481. if (needStencil) {
  26482. this._engine.setStencilBuffer(stencilState);
  26483. }
  26484. // Bounding boxes
  26485. if (this._boundingBoxRenderer) {
  26486. this._boundingBoxRenderer.render();
  26487. }
  26488. // Lens flares
  26489. if (this.lensFlaresEnabled) {
  26490. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26491. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26492. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26493. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26494. lensFlareSystem.render();
  26495. }
  26496. }
  26497. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26498. }
  26499. // Effect Layer
  26500. if (renderEffects) {
  26501. engine.setDepthBuffer(false);
  26502. for (var i = 0; i < this.effectLayers.length; i++) {
  26503. if (this.effectLayers[i].shouldRender()) {
  26504. this.effectLayers[i].render();
  26505. }
  26506. }
  26507. engine.setDepthBuffer(true);
  26508. }
  26509. // Foregrounds
  26510. if (this.layers.length) {
  26511. engine.setDepthBuffer(false);
  26512. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26513. layer = this.layers[layerIndex];
  26514. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26515. layer.render();
  26516. }
  26517. }
  26518. engine.setDepthBuffer(true);
  26519. }
  26520. // Finalize frame
  26521. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26522. // Reset some special arrays
  26523. this._renderTargets.reset();
  26524. this._alternateRendering = false;
  26525. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26526. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26527. };
  26528. Scene.prototype._processSubCameras = function (camera) {
  26529. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26530. this._renderForCamera(camera);
  26531. return;
  26532. }
  26533. // rig cameras
  26534. for (var index = 0; index < camera._rigCameras.length; index++) {
  26535. this._renderForCamera(camera._rigCameras[index], camera);
  26536. }
  26537. this.activeCamera = camera;
  26538. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26539. };
  26540. Scene.prototype._checkIntersections = function () {
  26541. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26542. var sourceMesh = this._meshesForIntersections.data[index];
  26543. if (!sourceMesh.actionManager) {
  26544. continue;
  26545. }
  26546. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26547. var action = sourceMesh.actionManager.actions[actionIndex];
  26548. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26549. var parameters = action.getTriggerParameter();
  26550. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26551. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26552. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26553. if (areIntersecting && currentIntersectionInProgress === -1) {
  26554. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26555. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26556. sourceMesh._intersectionsInProgress.push(otherMesh);
  26557. }
  26558. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26559. sourceMesh._intersectionsInProgress.push(otherMesh);
  26560. }
  26561. }
  26562. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26563. //They intersected, and now they don't.
  26564. //is this trigger an exit trigger? execute an event.
  26565. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26566. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26567. }
  26568. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26569. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26570. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26571. }
  26572. }
  26573. }
  26574. }
  26575. }
  26576. };
  26577. /**
  26578. * Render the scene
  26579. */
  26580. Scene.prototype.render = function () {
  26581. if (this.isDisposed) {
  26582. return;
  26583. }
  26584. this._activeParticles.fetchNewFrame();
  26585. this._totalVertices.fetchNewFrame();
  26586. this._activeIndices.fetchNewFrame();
  26587. this._activeBones.fetchNewFrame();
  26588. this._meshesForIntersections.reset();
  26589. this.resetCachedMaterial();
  26590. this.onBeforeAnimationsObservable.notifyObservers(this);
  26591. // Actions
  26592. if (this.actionManager) {
  26593. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26594. }
  26595. //Simplification Queue
  26596. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26597. this.simplificationQueue.executeNext();
  26598. }
  26599. if (this._engine.isDeterministicLockStep()) {
  26600. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26601. var defaultFPS = (60.0 / 1000.0);
  26602. var defaultFrameTime = 1000 / 60; // frame time in MS
  26603. if (this._physicsEngine) {
  26604. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26605. }
  26606. var stepsTaken = 0;
  26607. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26608. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26609. internalSteps = Math.min(internalSteps, maxSubSteps);
  26610. do {
  26611. this.onBeforeStepObservable.notifyObservers(this);
  26612. // Animations
  26613. this._animationRatio = defaultFrameTime * defaultFPS;
  26614. this._animate();
  26615. this.onAfterAnimationsObservable.notifyObservers(this);
  26616. // Physics
  26617. if (this._physicsEngine) {
  26618. this.onBeforePhysicsObservable.notifyObservers(this);
  26619. this._physicsEngine._step(defaultFrameTime / 1000);
  26620. this.onAfterPhysicsObservable.notifyObservers(this);
  26621. }
  26622. this.onAfterStepObservable.notifyObservers(this);
  26623. this._currentStepId++;
  26624. stepsTaken++;
  26625. deltaTime -= defaultFrameTime;
  26626. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26627. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26628. }
  26629. else {
  26630. // Animations
  26631. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26632. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26633. this._animate();
  26634. this.onAfterAnimationsObservable.notifyObservers(this);
  26635. // Physics
  26636. if (this._physicsEngine) {
  26637. this.onBeforePhysicsObservable.notifyObservers(this);
  26638. this._physicsEngine._step(deltaTime / 1000.0);
  26639. this.onAfterPhysicsObservable.notifyObservers(this);
  26640. }
  26641. }
  26642. // update gamepad manager
  26643. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26644. this._gamepadManager._checkGamepadsStatus();
  26645. }
  26646. // Update Cameras
  26647. if (this.activeCameras.length > 0) {
  26648. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26649. var camera = this.activeCameras[cameraIndex];
  26650. camera.update();
  26651. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26652. // rig cameras
  26653. for (var index = 0; index < camera._rigCameras.length; index++) {
  26654. camera._rigCameras[index].update();
  26655. }
  26656. }
  26657. }
  26658. }
  26659. else if (this.activeCamera) {
  26660. this.activeCamera.update();
  26661. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26662. // rig cameras
  26663. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26664. this.activeCamera._rigCameras[index].update();
  26665. }
  26666. }
  26667. }
  26668. // Before render
  26669. this.onBeforeRenderObservable.notifyObservers(this);
  26670. // Customs render targets
  26671. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26672. var engine = this.getEngine();
  26673. var currentActiveCamera = this.activeCamera;
  26674. if (this.renderTargetsEnabled) {
  26675. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26676. this._intermediateRendering = true;
  26677. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  26678. var renderTarget = this.customRenderTargets[customIndex];
  26679. if (renderTarget._shouldRender()) {
  26680. this._renderId++;
  26681. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  26682. if (!this.activeCamera)
  26683. throw new Error("Active camera not set");
  26684. // Viewport
  26685. engine.setViewport(this.activeCamera.viewport);
  26686. // Camera
  26687. this.updateTransformMatrix();
  26688. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  26689. }
  26690. }
  26691. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26692. this._intermediateRendering = false;
  26693. this._renderId++;
  26694. }
  26695. // Restore back buffer
  26696. if (this.customRenderTargets.length > 0) {
  26697. engine.restoreDefaultFramebuffer();
  26698. }
  26699. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26700. this.activeCamera = currentActiveCamera;
  26701. // Procedural textures
  26702. if (this.proceduralTexturesEnabled) {
  26703. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26704. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  26705. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  26706. if (proceduralTexture._shouldRender()) {
  26707. proceduralTexture.render();
  26708. }
  26709. }
  26710. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26711. }
  26712. // Clear
  26713. if (this.autoClearDepthAndStencil || this.autoClear) {
  26714. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  26715. }
  26716. // Shadows
  26717. if (this.shadowsEnabled) {
  26718. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  26719. var light = this.lights[lightIndex];
  26720. var shadowGenerator = light.getShadowGenerator();
  26721. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  26722. var shadowMap = (shadowGenerator.getShadowMap());
  26723. if (this.textures.indexOf(shadowMap) !== -1) {
  26724. this._renderTargets.push(shadowMap);
  26725. }
  26726. }
  26727. }
  26728. }
  26729. // Depth renderer
  26730. for (var key in this._depthRenderer) {
  26731. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  26732. }
  26733. // Geometry renderer
  26734. if (this._geometryBufferRenderer) {
  26735. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  26736. }
  26737. // RenderPipeline
  26738. if (this._postProcessRenderPipelineManager) {
  26739. this._postProcessRenderPipelineManager.update();
  26740. }
  26741. // Multi-cameras?
  26742. if (this.activeCameras.length > 0) {
  26743. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26744. if (cameraIndex > 0) {
  26745. this._engine.clear(null, false, true, true);
  26746. }
  26747. this._processSubCameras(this.activeCameras[cameraIndex]);
  26748. }
  26749. }
  26750. else {
  26751. if (!this.activeCamera) {
  26752. throw new Error("No camera defined");
  26753. }
  26754. this._processSubCameras(this.activeCamera);
  26755. }
  26756. // Intersection checks
  26757. this._checkIntersections();
  26758. // Update the audio listener attached to the camera
  26759. if (BABYLON.AudioEngine) {
  26760. this._updateAudioParameters();
  26761. }
  26762. // After render
  26763. if (this.afterRender) {
  26764. this.afterRender();
  26765. }
  26766. this.onAfterRenderObservable.notifyObservers(this);
  26767. // Cleaning
  26768. for (var index = 0; index < this._toBeDisposed.length; index++) {
  26769. var data = this._toBeDisposed.data[index];
  26770. if (data) {
  26771. data.dispose();
  26772. }
  26773. this._toBeDisposed[index] = null;
  26774. }
  26775. this._toBeDisposed.reset();
  26776. if (this.dumpNextRenderTargets) {
  26777. this.dumpNextRenderTargets = false;
  26778. }
  26779. this._activeBones.addCount(0, true);
  26780. this._activeIndices.addCount(0, true);
  26781. this._activeParticles.addCount(0, true);
  26782. };
  26783. Scene.prototype._updateAudioParameters = function () {
  26784. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  26785. return;
  26786. }
  26787. var listeningCamera;
  26788. var audioEngine = BABYLON.Engine.audioEngine;
  26789. if (this.activeCameras.length > 0) {
  26790. listeningCamera = this.activeCameras[0];
  26791. }
  26792. else {
  26793. listeningCamera = this.activeCamera;
  26794. }
  26795. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  26796. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  26797. // for VR cameras
  26798. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  26799. listeningCamera = listeningCamera.rigCameras[0];
  26800. }
  26801. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  26802. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  26803. cameraDirection.normalize();
  26804. // To avoid some errors on GearVR
  26805. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  26806. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  26807. }
  26808. var i;
  26809. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26810. var sound = this.mainSoundTrack.soundCollection[i];
  26811. if (sound.useCustomAttenuation) {
  26812. sound.updateDistanceFromListener();
  26813. }
  26814. }
  26815. for (i = 0; i < this.soundTracks.length; i++) {
  26816. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26817. sound = this.soundTracks[i].soundCollection[j];
  26818. if (sound.useCustomAttenuation) {
  26819. sound.updateDistanceFromListener();
  26820. }
  26821. }
  26822. }
  26823. }
  26824. };
  26825. Object.defineProperty(Scene.prototype, "audioEnabled", {
  26826. // Audio
  26827. /**
  26828. * Gets or sets if audio support is enabled
  26829. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  26830. */
  26831. get: function () {
  26832. return this._audioEnabled;
  26833. },
  26834. set: function (value) {
  26835. this._audioEnabled = value;
  26836. if (BABYLON.AudioEngine) {
  26837. if (this._audioEnabled) {
  26838. this._enableAudio();
  26839. }
  26840. else {
  26841. this._disableAudio();
  26842. }
  26843. }
  26844. },
  26845. enumerable: true,
  26846. configurable: true
  26847. });
  26848. Scene.prototype._disableAudio = function () {
  26849. var i;
  26850. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26851. this.mainSoundTrack.soundCollection[i].pause();
  26852. }
  26853. for (i = 0; i < this.soundTracks.length; i++) {
  26854. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26855. this.soundTracks[i].soundCollection[j].pause();
  26856. }
  26857. }
  26858. };
  26859. Scene.prototype._enableAudio = function () {
  26860. var i;
  26861. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26862. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  26863. this.mainSoundTrack.soundCollection[i].play();
  26864. }
  26865. }
  26866. for (i = 0; i < this.soundTracks.length; i++) {
  26867. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26868. if (this.soundTracks[i].soundCollection[j].isPaused) {
  26869. this.soundTracks[i].soundCollection[j].play();
  26870. }
  26871. }
  26872. }
  26873. };
  26874. Object.defineProperty(Scene.prototype, "headphone", {
  26875. /**
  26876. * Gets or sets if audio will be output to headphones
  26877. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  26878. */
  26879. get: function () {
  26880. return this._headphone;
  26881. },
  26882. set: function (value) {
  26883. this._headphone = value;
  26884. if (BABYLON.AudioEngine) {
  26885. if (this._headphone) {
  26886. this._switchAudioModeForHeadphones();
  26887. }
  26888. else {
  26889. this._switchAudioModeForNormalSpeakers();
  26890. }
  26891. }
  26892. },
  26893. enumerable: true,
  26894. configurable: true
  26895. });
  26896. Scene.prototype._switchAudioModeForHeadphones = function () {
  26897. this.mainSoundTrack.switchPanningModelToHRTF();
  26898. for (var i = 0; i < this.soundTracks.length; i++) {
  26899. this.soundTracks[i].switchPanningModelToHRTF();
  26900. }
  26901. };
  26902. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  26903. this.mainSoundTrack.switchPanningModelToEqualPower();
  26904. for (var i = 0; i < this.soundTracks.length; i++) {
  26905. this.soundTracks[i].switchPanningModelToEqualPower();
  26906. }
  26907. };
  26908. /**
  26909. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  26910. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  26911. * @returns the created depth renderer
  26912. */
  26913. Scene.prototype.enableDepthRenderer = function (camera) {
  26914. camera = camera || this.activeCamera;
  26915. if (!camera) {
  26916. throw "No camera available to enable depth renderer";
  26917. }
  26918. if (!this._depthRenderer[camera.id]) {
  26919. var textureType = 0;
  26920. if (this._engine.getCaps().textureHalfFloatRender) {
  26921. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  26922. }
  26923. else if (this._engine.getCaps().textureFloatRender) {
  26924. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  26925. }
  26926. else {
  26927. throw "Depth renderer does not support int texture type";
  26928. }
  26929. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  26930. }
  26931. return this._depthRenderer[camera.id];
  26932. };
  26933. /**
  26934. * Disables a depth renderer for a given camera
  26935. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  26936. */
  26937. Scene.prototype.disableDepthRenderer = function (camera) {
  26938. camera = camera || this.activeCamera;
  26939. if (!camera || !this._depthRenderer[camera.id]) {
  26940. return;
  26941. }
  26942. this._depthRenderer[camera.id].dispose();
  26943. delete this._depthRenderer[camera.id];
  26944. };
  26945. /**
  26946. * Enables a GeometryBufferRender and associates it with the scene
  26947. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  26948. * @returns the GeometryBufferRenderer
  26949. */
  26950. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  26951. if (ratio === void 0) { ratio = 1; }
  26952. if (this._geometryBufferRenderer) {
  26953. return this._geometryBufferRenderer;
  26954. }
  26955. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  26956. if (!this._geometryBufferRenderer.isSupported) {
  26957. this._geometryBufferRenderer = null;
  26958. }
  26959. return this._geometryBufferRenderer;
  26960. };
  26961. /**
  26962. * Disables the GeometryBufferRender associated with the scene
  26963. */
  26964. Scene.prototype.disableGeometryBufferRenderer = function () {
  26965. if (!this._geometryBufferRenderer) {
  26966. return;
  26967. }
  26968. this._geometryBufferRenderer.dispose();
  26969. this._geometryBufferRenderer = null;
  26970. };
  26971. /**
  26972. * Freeze all materials
  26973. * A frozen material will not be updatable but should be faster to render
  26974. */
  26975. Scene.prototype.freezeMaterials = function () {
  26976. for (var i = 0; i < this.materials.length; i++) {
  26977. this.materials[i].freeze();
  26978. }
  26979. };
  26980. /**
  26981. * Unfreeze all materials
  26982. * A frozen material will not be updatable but should be faster to render
  26983. */
  26984. Scene.prototype.unfreezeMaterials = function () {
  26985. for (var i = 0; i < this.materials.length; i++) {
  26986. this.materials[i].unfreeze();
  26987. }
  26988. };
  26989. /**
  26990. * Releases all held ressources
  26991. */
  26992. Scene.prototype.dispose = function () {
  26993. this.beforeRender = null;
  26994. this.afterRender = null;
  26995. this.skeletons = [];
  26996. this.morphTargetManagers = [];
  26997. this.importedMeshesFiles = new Array();
  26998. this.stopAllAnimations();
  26999. this.resetCachedMaterial();
  27000. for (var key in this._depthRenderer) {
  27001. this._depthRenderer[key].dispose();
  27002. }
  27003. if (this._gamepadManager) {
  27004. this._gamepadManager.dispose();
  27005. this._gamepadManager = null;
  27006. }
  27007. // Smart arrays
  27008. if (this.activeCamera) {
  27009. this.activeCamera._activeMeshes.dispose();
  27010. this.activeCamera = null;
  27011. }
  27012. this._activeMeshes.dispose();
  27013. this._renderingManager.dispose();
  27014. this._processedMaterials.dispose();
  27015. this._activeParticleSystems.dispose();
  27016. this._activeSkeletons.dispose();
  27017. this._softwareSkinnedMeshes.dispose();
  27018. this._renderTargets.dispose();
  27019. this._registeredForLateAnimationBindings.dispose();
  27020. if (this._boundingBoxRenderer) {
  27021. this._boundingBoxRenderer.dispose();
  27022. }
  27023. this._meshesForIntersections.dispose();
  27024. this._toBeDisposed.dispose();
  27025. // Abort active requests
  27026. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27027. var request = _a[_i];
  27028. request.abort();
  27029. }
  27030. // Debug layer
  27031. if (this._debugLayer) {
  27032. this._debugLayer.hide();
  27033. }
  27034. // Events
  27035. this.onDisposeObservable.notifyObservers(this);
  27036. this.onDisposeObservable.clear();
  27037. this.onBeforeRenderObservable.clear();
  27038. this.onAfterRenderObservable.clear();
  27039. this.onBeforeRenderTargetsRenderObservable.clear();
  27040. this.onAfterRenderTargetsRenderObservable.clear();
  27041. this.onAfterStepObservable.clear();
  27042. this.onBeforeStepObservable.clear();
  27043. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27044. this.onAfterActiveMeshesEvaluationObservable.clear();
  27045. this.onBeforeParticlesRenderingObservable.clear();
  27046. this.onAfterParticlesRenderingObservable.clear();
  27047. this.onBeforeSpritesRenderingObservable.clear();
  27048. this.onAfterSpritesRenderingObservable.clear();
  27049. this.onBeforeDrawPhaseObservable.clear();
  27050. this.onAfterDrawPhaseObservable.clear();
  27051. this.onBeforePhysicsObservable.clear();
  27052. this.onAfterPhysicsObservable.clear();
  27053. this.onBeforeAnimationsObservable.clear();
  27054. this.onAfterAnimationsObservable.clear();
  27055. this.onDataLoadedObservable.clear();
  27056. this.detachControl();
  27057. // Release sounds & sounds tracks
  27058. if (BABYLON.AudioEngine) {
  27059. this.disposeSounds();
  27060. }
  27061. // VR Helper
  27062. if (this.VRHelper) {
  27063. this.VRHelper.dispose();
  27064. }
  27065. // Detach cameras
  27066. var canvas = this._engine.getRenderingCanvas();
  27067. if (canvas) {
  27068. var index;
  27069. for (index = 0; index < this.cameras.length; index++) {
  27070. this.cameras[index].detachControl(canvas);
  27071. }
  27072. }
  27073. // Release animation groups
  27074. while (this.animationGroups.length) {
  27075. this.animationGroups[0].dispose();
  27076. }
  27077. // Release lights
  27078. while (this.lights.length) {
  27079. this.lights[0].dispose();
  27080. }
  27081. // Release meshes
  27082. while (this.meshes.length) {
  27083. this.meshes[0].dispose(true);
  27084. }
  27085. while (this.transformNodes.length) {
  27086. this.removeTransformNode(this.transformNodes[0]);
  27087. }
  27088. // Release cameras
  27089. while (this.cameras.length) {
  27090. this.cameras[0].dispose();
  27091. }
  27092. // Release materials
  27093. if (this.defaultMaterial) {
  27094. this.defaultMaterial.dispose();
  27095. }
  27096. while (this.multiMaterials.length) {
  27097. this.multiMaterials[0].dispose();
  27098. }
  27099. while (this.materials.length) {
  27100. this.materials[0].dispose();
  27101. }
  27102. // Release particles
  27103. while (this.particleSystems.length) {
  27104. this.particleSystems[0].dispose();
  27105. }
  27106. // Release sprites
  27107. while (this.spriteManagers.length) {
  27108. this.spriteManagers[0].dispose();
  27109. }
  27110. // Release postProcesses
  27111. while (this.postProcesses.length) {
  27112. this.postProcesses[0].dispose();
  27113. }
  27114. // Release layers
  27115. while (this.layers.length) {
  27116. this.layers[0].dispose();
  27117. }
  27118. while (this.effectLayers.length) {
  27119. this.effectLayers[0].dispose();
  27120. }
  27121. // Release textures
  27122. while (this.textures.length) {
  27123. this.textures[0].dispose();
  27124. }
  27125. // Release UBO
  27126. this._sceneUbo.dispose();
  27127. if (this._alternateSceneUbo) {
  27128. this._alternateSceneUbo.dispose();
  27129. }
  27130. // Post-processes
  27131. this.postProcessManager.dispose();
  27132. if (this._postProcessRenderPipelineManager) {
  27133. this._postProcessRenderPipelineManager.dispose();
  27134. }
  27135. // Physics
  27136. if (this._physicsEngine) {
  27137. this.disablePhysicsEngine();
  27138. }
  27139. // Remove from engine
  27140. index = this._engine.scenes.indexOf(this);
  27141. if (index > -1) {
  27142. this._engine.scenes.splice(index, 1);
  27143. }
  27144. this._engine.wipeCaches(true);
  27145. this._isDisposed = true;
  27146. };
  27147. Object.defineProperty(Scene.prototype, "isDisposed", {
  27148. /**
  27149. * Gets if the scene is already disposed
  27150. */
  27151. get: function () {
  27152. return this._isDisposed;
  27153. },
  27154. enumerable: true,
  27155. configurable: true
  27156. });
  27157. /**
  27158. * Releases sounds & soundtracks
  27159. */
  27160. Scene.prototype.disposeSounds = function () {
  27161. if (!this._mainSoundTrack) {
  27162. return;
  27163. }
  27164. this.mainSoundTrack.dispose();
  27165. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27166. this.soundTracks[scIndex].dispose();
  27167. }
  27168. };
  27169. // Octrees
  27170. /**
  27171. * Get the world extend vectors with an optional filter
  27172. *
  27173. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27174. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27175. */
  27176. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27177. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27178. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27179. filterPredicate = filterPredicate || (function () { return true; });
  27180. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27181. mesh.computeWorldMatrix(true);
  27182. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27183. return;
  27184. }
  27185. var boundingInfo = mesh.getBoundingInfo();
  27186. var minBox = boundingInfo.boundingBox.minimumWorld;
  27187. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27188. BABYLON.Tools.CheckExtends(minBox, min, max);
  27189. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27190. });
  27191. return {
  27192. min: min,
  27193. max: max
  27194. };
  27195. };
  27196. /**
  27197. * Creates or updates the octree used to boost selection (picking)
  27198. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27199. * @param maxCapacity defines the maximum capacity per leaf
  27200. * @param maxDepth defines the maximum depth of the octree
  27201. * @returns an octree of AbstractMesh
  27202. */
  27203. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27204. if (maxCapacity === void 0) { maxCapacity = 64; }
  27205. if (maxDepth === void 0) { maxDepth = 2; }
  27206. if (!this._selectionOctree) {
  27207. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27208. }
  27209. var worldExtends = this.getWorldExtends();
  27210. // Update octree
  27211. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27212. return this._selectionOctree;
  27213. };
  27214. // Picking
  27215. /**
  27216. * Creates a ray that can be used to pick in the scene
  27217. * @param x defines the x coordinate of the origin (on-screen)
  27218. * @param y defines the y coordinate of the origin (on-screen)
  27219. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27220. * @param camera defines the camera to use for the picking
  27221. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27222. * @returns a Ray
  27223. */
  27224. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27225. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27226. var result = BABYLON.Ray.Zero();
  27227. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27228. return result;
  27229. };
  27230. /**
  27231. * Creates a ray that can be used to pick in the scene
  27232. * @param x defines the x coordinate of the origin (on-screen)
  27233. * @param y defines the y coordinate of the origin (on-screen)
  27234. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27235. * @param result defines the ray where to store the picking ray
  27236. * @param camera defines the camera to use for the picking
  27237. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27238. * @returns the current scene
  27239. */
  27240. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27241. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27242. var engine = this._engine;
  27243. if (!camera) {
  27244. if (!this.activeCamera)
  27245. throw new Error("Active camera not set");
  27246. camera = this.activeCamera;
  27247. }
  27248. var cameraViewport = camera.viewport;
  27249. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27250. // Moving coordinates to local viewport world
  27251. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27252. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27253. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27254. return this;
  27255. };
  27256. /**
  27257. * Creates a ray that can be used to pick in the scene
  27258. * @param x defines the x coordinate of the origin (on-screen)
  27259. * @param y defines the y coordinate of the origin (on-screen)
  27260. * @param camera defines the camera to use for the picking
  27261. * @returns a Ray
  27262. */
  27263. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27264. var result = BABYLON.Ray.Zero();
  27265. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27266. return result;
  27267. };
  27268. /**
  27269. * Creates a ray that can be used to pick in the scene
  27270. * @param x defines the x coordinate of the origin (on-screen)
  27271. * @param y defines the y coordinate of the origin (on-screen)
  27272. * @param result defines the ray where to store the picking ray
  27273. * @param camera defines the camera to use for the picking
  27274. * @returns the current scene
  27275. */
  27276. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27277. if (!BABYLON.PickingInfo) {
  27278. return this;
  27279. }
  27280. var engine = this._engine;
  27281. if (!camera) {
  27282. if (!this.activeCamera)
  27283. throw new Error("Active camera not set");
  27284. camera = this.activeCamera;
  27285. }
  27286. var cameraViewport = camera.viewport;
  27287. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27288. var identity = BABYLON.Matrix.Identity();
  27289. // Moving coordinates to local viewport world
  27290. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27291. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27292. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27293. return this;
  27294. };
  27295. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27296. if (!BABYLON.PickingInfo) {
  27297. return null;
  27298. }
  27299. var pickingInfo = null;
  27300. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27301. var mesh = this.meshes[meshIndex];
  27302. if (predicate) {
  27303. if (!predicate(mesh)) {
  27304. continue;
  27305. }
  27306. }
  27307. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27308. continue;
  27309. }
  27310. var world = mesh.getWorldMatrix();
  27311. var ray = rayFunction(world);
  27312. var result = mesh.intersects(ray, fastCheck);
  27313. if (!result || !result.hit)
  27314. continue;
  27315. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27316. continue;
  27317. pickingInfo = result;
  27318. if (fastCheck) {
  27319. break;
  27320. }
  27321. }
  27322. return pickingInfo || new BABYLON.PickingInfo();
  27323. };
  27324. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27325. if (!BABYLON.PickingInfo) {
  27326. return null;
  27327. }
  27328. var pickingInfos = new Array();
  27329. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27330. var mesh = this.meshes[meshIndex];
  27331. if (predicate) {
  27332. if (!predicate(mesh)) {
  27333. continue;
  27334. }
  27335. }
  27336. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27337. continue;
  27338. }
  27339. var world = mesh.getWorldMatrix();
  27340. var ray = rayFunction(world);
  27341. var result = mesh.intersects(ray, false);
  27342. if (!result || !result.hit)
  27343. continue;
  27344. pickingInfos.push(result);
  27345. }
  27346. return pickingInfos;
  27347. };
  27348. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27349. if (!BABYLON.PickingInfo) {
  27350. return null;
  27351. }
  27352. var pickingInfo = null;
  27353. if (!camera) {
  27354. if (!this.activeCamera) {
  27355. return null;
  27356. }
  27357. camera = this.activeCamera;
  27358. }
  27359. if (this.spriteManagers.length > 0) {
  27360. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27361. var spriteManager = this.spriteManagers[spriteIndex];
  27362. if (!spriteManager.isPickable) {
  27363. continue;
  27364. }
  27365. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27366. if (!result || !result.hit)
  27367. continue;
  27368. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27369. continue;
  27370. pickingInfo = result;
  27371. if (fastCheck) {
  27372. break;
  27373. }
  27374. }
  27375. }
  27376. return pickingInfo || new BABYLON.PickingInfo();
  27377. };
  27378. /** Launch a ray to try to pick a mesh in the scene
  27379. * @param x position on screen
  27380. * @param y position on screen
  27381. * @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
  27382. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27383. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27384. * @returns a PickingInfo
  27385. */
  27386. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27387. var _this = this;
  27388. if (!BABYLON.PickingInfo) {
  27389. return null;
  27390. }
  27391. return this._internalPick(function (world) {
  27392. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27393. return _this._tempPickingRay;
  27394. }, predicate, fastCheck);
  27395. };
  27396. /** Launch a ray to try to pick a sprite in the scene
  27397. * @param x position on screen
  27398. * @param y position on screen
  27399. * @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
  27400. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27401. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27402. * @returns a PickingInfo
  27403. */
  27404. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27405. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27406. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27407. };
  27408. /** Use the given ray to pick a mesh in the scene
  27409. * @param ray The ray to use to pick meshes
  27410. * @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
  27411. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27412. * @returns a PickingInfo
  27413. */
  27414. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27415. var _this = this;
  27416. return this._internalPick(function (world) {
  27417. if (!_this._pickWithRayInverseMatrix) {
  27418. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27419. }
  27420. world.invertToRef(_this._pickWithRayInverseMatrix);
  27421. if (!_this._cachedRayForTransform) {
  27422. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27423. }
  27424. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27425. return _this._cachedRayForTransform;
  27426. }, predicate, fastCheck);
  27427. };
  27428. /**
  27429. * Launch a ray to try to pick a mesh in the scene
  27430. * @param x X position on screen
  27431. * @param y Y position on screen
  27432. * @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
  27433. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27434. * @returns an array of PickingInfo
  27435. */
  27436. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27437. var _this = this;
  27438. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27439. };
  27440. /**
  27441. * Launch a ray to try to pick a mesh in the scene
  27442. * @param ray Ray to use
  27443. * @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
  27444. * @returns an array of PickingInfo
  27445. */
  27446. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27447. var _this = this;
  27448. return this._internalMultiPick(function (world) {
  27449. if (!_this._pickWithRayInverseMatrix) {
  27450. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27451. }
  27452. world.invertToRef(_this._pickWithRayInverseMatrix);
  27453. if (!_this._cachedRayForTransform) {
  27454. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27455. }
  27456. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27457. return _this._cachedRayForTransform;
  27458. }, predicate);
  27459. };
  27460. /**
  27461. * Force the value of meshUnderPointer
  27462. * @param mesh defines the mesh to use
  27463. */
  27464. Scene.prototype.setPointerOverMesh = function (mesh) {
  27465. if (this._pointerOverMesh === mesh) {
  27466. return;
  27467. }
  27468. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27469. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27470. }
  27471. this._pointerOverMesh = mesh;
  27472. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27473. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27474. }
  27475. };
  27476. /**
  27477. * Gets the mesh under the pointer
  27478. * @returns a Mesh or null if no mesh is under the pointer
  27479. */
  27480. Scene.prototype.getPointerOverMesh = function () {
  27481. return this._pointerOverMesh;
  27482. };
  27483. /**
  27484. * Force the sprite under the pointer
  27485. * @param sprite defines the sprite to use
  27486. */
  27487. Scene.prototype.setPointerOverSprite = function (sprite) {
  27488. if (this._pointerOverSprite === sprite) {
  27489. return;
  27490. }
  27491. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27492. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27493. }
  27494. this._pointerOverSprite = sprite;
  27495. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27496. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27497. }
  27498. };
  27499. /**
  27500. * Gets the sprite under the pointer
  27501. * @returns a Sprite or null if no sprite is under the pointer
  27502. */
  27503. Scene.prototype.getPointerOverSprite = function () {
  27504. return this._pointerOverSprite;
  27505. };
  27506. // Physics
  27507. /**
  27508. * Gets the current physics engine
  27509. * @returns a PhysicsEngine or null if none attached
  27510. */
  27511. Scene.prototype.getPhysicsEngine = function () {
  27512. return this._physicsEngine;
  27513. };
  27514. /**
  27515. * Enables physics to the current scene
  27516. * @param gravity defines the scene's gravity for the physics engine
  27517. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27518. * @return a boolean indicating if the physics engine was initialized
  27519. */
  27520. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27521. if (gravity === void 0) { gravity = null; }
  27522. if (this._physicsEngine) {
  27523. return true;
  27524. }
  27525. try {
  27526. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27527. return true;
  27528. }
  27529. catch (e) {
  27530. BABYLON.Tools.Error(e.message);
  27531. return false;
  27532. }
  27533. };
  27534. /**
  27535. * Disables and disposes the physics engine associated with the scene
  27536. */
  27537. Scene.prototype.disablePhysicsEngine = function () {
  27538. if (!this._physicsEngine) {
  27539. return;
  27540. }
  27541. this._physicsEngine.dispose();
  27542. this._physicsEngine = null;
  27543. };
  27544. /**
  27545. * Gets a boolean indicating if there is an active physics engine
  27546. * @returns a boolean indicating if there is an active physics engine
  27547. */
  27548. Scene.prototype.isPhysicsEnabled = function () {
  27549. return this._physicsEngine !== undefined;
  27550. };
  27551. /**
  27552. * Deletes a physics compound impostor
  27553. * @param compound defines the compound to delete
  27554. */
  27555. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27556. var mesh = compound.parts[0].mesh;
  27557. if (mesh.physicsImpostor) {
  27558. mesh.physicsImpostor.dispose();
  27559. mesh.physicsImpostor = null;
  27560. }
  27561. };
  27562. // Misc.
  27563. /** @ignore */
  27564. Scene.prototype._rebuildGeometries = function () {
  27565. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27566. var geometry = _a[_i];
  27567. geometry._rebuild();
  27568. }
  27569. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27570. var mesh = _c[_b];
  27571. mesh._rebuild();
  27572. }
  27573. if (this.postProcessManager) {
  27574. this.postProcessManager._rebuild();
  27575. }
  27576. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27577. var layer = _e[_d];
  27578. layer._rebuild();
  27579. }
  27580. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27581. var effectLayer = _g[_f];
  27582. effectLayer._rebuild();
  27583. }
  27584. if (this._boundingBoxRenderer) {
  27585. this._boundingBoxRenderer._rebuild();
  27586. }
  27587. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27588. var system = _j[_h];
  27589. system.rebuild();
  27590. }
  27591. if (this._postProcessRenderPipelineManager) {
  27592. this._postProcessRenderPipelineManager._rebuild();
  27593. }
  27594. };
  27595. /** @ignore */
  27596. Scene.prototype._rebuildTextures = function () {
  27597. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27598. var texture = _a[_i];
  27599. texture._rebuild();
  27600. }
  27601. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27602. };
  27603. /**
  27604. * Creates a default light for the scene.
  27605. * @param replace Whether to replace the existing lights in the scene.
  27606. */
  27607. Scene.prototype.createDefaultLight = function (replace) {
  27608. if (replace === void 0) { replace = false; }
  27609. // Dispose existing light in replace mode.
  27610. if (replace) {
  27611. if (this.lights) {
  27612. for (var i = 0; i < this.lights.length; i++) {
  27613. this.lights[i].dispose();
  27614. }
  27615. }
  27616. }
  27617. // Light
  27618. if (this.lights.length === 0) {
  27619. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27620. }
  27621. };
  27622. /**
  27623. * Creates a default camera for the scene.
  27624. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27625. * @param replace Whether to replace the existing active camera in the scene.
  27626. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27627. */
  27628. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27629. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27630. if (replace === void 0) { replace = false; }
  27631. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27632. // Dispose existing camera in replace mode.
  27633. if (replace) {
  27634. if (this.activeCamera) {
  27635. this.activeCamera.dispose();
  27636. this.activeCamera = null;
  27637. }
  27638. }
  27639. // Camera
  27640. if (!this.activeCamera) {
  27641. var worldExtends = this.getWorldExtends();
  27642. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27643. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27644. var camera;
  27645. var radius = worldSize.length() * 1.5;
  27646. // empty scene scenario!
  27647. if (!isFinite(radius)) {
  27648. radius = 1;
  27649. worldCenter.copyFromFloats(0, 0, 0);
  27650. }
  27651. if (createArcRotateCamera) {
  27652. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27653. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27654. arcRotateCamera.wheelPrecision = 100 / radius;
  27655. camera = arcRotateCamera;
  27656. }
  27657. else {
  27658. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27659. freeCamera.setTarget(worldCenter);
  27660. camera = freeCamera;
  27661. }
  27662. camera.minZ = radius * 0.01;
  27663. camera.maxZ = radius * 1000;
  27664. camera.speed = radius * 0.2;
  27665. this.activeCamera = camera;
  27666. var canvas = this.getEngine().getRenderingCanvas();
  27667. if (attachCameraControls && canvas) {
  27668. camera.attachControl(canvas);
  27669. }
  27670. }
  27671. };
  27672. /**
  27673. * Creates a default camera and a default light
  27674. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  27675. * @param replace defines if the camera and/or light will replace the existing ones
  27676. * @param attachCameraControls defines if attachControl will be called on the new camera
  27677. */
  27678. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  27679. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27680. if (replace === void 0) { replace = false; }
  27681. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27682. this.createDefaultLight(replace);
  27683. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  27684. };
  27685. /**
  27686. * Creates a new sky box
  27687. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27688. * @param environmentTexture defines the texture to use as environment texture
  27689. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  27690. * @param scale defines the overall scale of the skybox
  27691. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  27692. * @returns a new mesh holding the sky box
  27693. */
  27694. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  27695. if (pbr === void 0) { pbr = false; }
  27696. if (scale === void 0) { scale = 1000; }
  27697. if (blur === void 0) { blur = 0; }
  27698. if (environmentTexture) {
  27699. this.environmentTexture = environmentTexture;
  27700. }
  27701. if (!this.environmentTexture) {
  27702. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  27703. return null;
  27704. }
  27705. // Skybox
  27706. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  27707. if (pbr) {
  27708. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  27709. hdrSkyboxMaterial.backFaceCulling = false;
  27710. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27711. if (hdrSkyboxMaterial.reflectionTexture) {
  27712. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27713. }
  27714. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  27715. hdrSkyboxMaterial.disableLighting = true;
  27716. hdrSkyboxMaterial.twoSidedLighting = true;
  27717. hdrSkybox.infiniteDistance = true;
  27718. hdrSkybox.material = hdrSkyboxMaterial;
  27719. }
  27720. else {
  27721. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  27722. skyboxMaterial.backFaceCulling = false;
  27723. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27724. if (skyboxMaterial.reflectionTexture) {
  27725. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27726. }
  27727. skyboxMaterial.disableLighting = true;
  27728. hdrSkybox.infiniteDistance = true;
  27729. hdrSkybox.material = skyboxMaterial;
  27730. }
  27731. return hdrSkybox;
  27732. };
  27733. /**
  27734. * Creates a new environment
  27735. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27736. * @param options defines the options you can use to configure the environment
  27737. * @returns the new EnvironmentHelper
  27738. */
  27739. Scene.prototype.createDefaultEnvironment = function (options) {
  27740. if (BABYLON.EnvironmentHelper) {
  27741. return new BABYLON.EnvironmentHelper(options, this);
  27742. }
  27743. return null;
  27744. };
  27745. /**
  27746. * Creates a new VREXperienceHelper
  27747. * @see http://doc.babylonjs.com/how_to/webvr_helper
  27748. * @param webVROptions defines the options used to create the new VREXperienceHelper
  27749. * @returns a new VREXperienceHelper
  27750. */
  27751. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  27752. if (webVROptions === void 0) { webVROptions = {}; }
  27753. return new BABYLON.VRExperienceHelper(this, webVROptions);
  27754. };
  27755. // Tags
  27756. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  27757. if (tagsQuery === undefined) {
  27758. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  27759. return list;
  27760. }
  27761. var listByTags = [];
  27762. forEach = forEach || (function (item) { return; });
  27763. for (var i in list) {
  27764. var item = list[i];
  27765. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  27766. listByTags.push(item);
  27767. forEach(item);
  27768. }
  27769. }
  27770. return listByTags;
  27771. };
  27772. /**
  27773. * Get a list of meshes by tags
  27774. * @param tagsQuery defines the tags query to use
  27775. * @param forEach defines a predicate used to filter results
  27776. * @returns an array of Mesh
  27777. */
  27778. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  27779. return this._getByTags(this.meshes, tagsQuery, forEach);
  27780. };
  27781. /**
  27782. * Get a list of cameras by tags
  27783. * @param tagsQuery defines the tags query to use
  27784. * @param forEach defines a predicate used to filter results
  27785. * @returns an array of Camera
  27786. */
  27787. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  27788. return this._getByTags(this.cameras, tagsQuery, forEach);
  27789. };
  27790. /**
  27791. * Get a list of lights by tags
  27792. * @param tagsQuery defines the tags query to use
  27793. * @param forEach defines a predicate used to filter results
  27794. * @returns an array of Light
  27795. */
  27796. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  27797. return this._getByTags(this.lights, tagsQuery, forEach);
  27798. };
  27799. /**
  27800. * Get a list of materials by tags
  27801. * @param tagsQuery defines the tags query to use
  27802. * @param forEach defines a predicate used to filter results
  27803. * @returns an array of Material
  27804. */
  27805. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  27806. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  27807. };
  27808. /**
  27809. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27810. * This allowed control for front to back rendering or reversly depending of the special needs.
  27811. *
  27812. * @param renderingGroupId The rendering group id corresponding to its index
  27813. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27814. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27815. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27816. */
  27817. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27818. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27819. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27820. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27821. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27822. };
  27823. /**
  27824. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27825. *
  27826. * @param renderingGroupId The rendering group id corresponding to its index
  27827. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27828. * @param depth Automatically clears depth between groups if true and autoClear is true.
  27829. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  27830. */
  27831. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  27832. if (depth === void 0) { depth = true; }
  27833. if (stencil === void 0) { stencil = true; }
  27834. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  27835. };
  27836. /**
  27837. * Will flag all materials as dirty to trigger new shader compilation
  27838. * @param flag defines the flag used to specify which material part must be marked as dirty
  27839. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  27840. */
  27841. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  27842. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  27843. var material = _a[_i];
  27844. if (predicate && !predicate(material)) {
  27845. continue;
  27846. }
  27847. material.markAsDirty(flag);
  27848. }
  27849. };
  27850. /** @ignore */
  27851. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  27852. var _this = this;
  27853. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  27854. this._activeRequests.push(request);
  27855. request.onCompleteObservable.add(function (request) {
  27856. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  27857. });
  27858. return request;
  27859. };
  27860. /** @ignore */
  27861. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  27862. var _this = this;
  27863. return new Promise(function (resolve, reject) {
  27864. _this._loadFile(url, function (data) {
  27865. resolve(data);
  27866. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  27867. reject(exception);
  27868. });
  27869. });
  27870. };
  27871. // Statics
  27872. Scene._FOGMODE_NONE = 0;
  27873. Scene._FOGMODE_EXP = 1;
  27874. Scene._FOGMODE_EXP2 = 2;
  27875. Scene._FOGMODE_LINEAR = 3;
  27876. Scene._uniqueIdCounter = 0;
  27877. /**
  27878. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  27879. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  27880. */
  27881. Scene.MinDeltaTime = 1.0;
  27882. /**
  27883. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  27884. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  27885. */
  27886. Scene.MaxDeltaTime = 1000.0;
  27887. /** The distance in pixel that you have to move to prevent some events */
  27888. Scene.DragMovementThreshold = 10; // in pixels
  27889. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  27890. Scene.LongPressDelay = 500; // in milliseconds
  27891. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  27892. Scene.DoubleClickDelay = 300; // in milliseconds
  27893. /** If you need to check double click without raising a single click at first click, enable this flag */
  27894. Scene.ExclusiveDoubleClickMode = false;
  27895. return Scene;
  27896. }());
  27897. BABYLON.Scene = Scene;
  27898. })(BABYLON || (BABYLON = {}));
  27899. //# sourceMappingURL=babylon.scene.js.map
  27900. "use strict";
  27901. var BABYLON;
  27902. (function (BABYLON) {
  27903. /**
  27904. * Set of assets to keep when moving a scene into an asset container.
  27905. */
  27906. var KeepAssets = /** @class */ (function () {
  27907. function KeepAssets() {
  27908. /**
  27909. * Cameras to keep.
  27910. */
  27911. this.cameras = new Array();
  27912. /**
  27913. * Lights to keep.
  27914. */
  27915. this.lights = new Array();
  27916. /**
  27917. * Meshes to keep.
  27918. */
  27919. this.meshes = new Array();
  27920. /**
  27921. * Skeletons to keep.
  27922. */
  27923. this.skeletons = new Array();
  27924. /**
  27925. * ParticleSystems to keep.
  27926. */
  27927. this.particleSystems = new Array();
  27928. /**
  27929. * Animations to keep.
  27930. */
  27931. this.animations = new Array();
  27932. /**
  27933. * AnimationGroups to keep.
  27934. */
  27935. this.animationGroups = new Array();
  27936. /**
  27937. * MultiMaterials to keep.
  27938. */
  27939. this.multiMaterials = new Array();
  27940. /**
  27941. * Materials to keep.
  27942. */
  27943. this.materials = new Array();
  27944. /**
  27945. * MorphTargetManagers to keep.
  27946. */
  27947. this.morphTargetManagers = new Array();
  27948. /**
  27949. * Geometries to keep.
  27950. */
  27951. this.geometries = new Array();
  27952. /**
  27953. * TransformNodes to keep.
  27954. */
  27955. this.transformNodes = new Array();
  27956. /**
  27957. * LensFlareSystems to keep.
  27958. */
  27959. this.lensFlareSystems = new Array();
  27960. /**
  27961. * ShadowGenerators to keep.
  27962. */
  27963. this.shadowGenerators = new Array();
  27964. /**
  27965. * ActionManagers to keep.
  27966. */
  27967. this.actionManagers = new Array();
  27968. /**
  27969. * Sounds to keep.
  27970. */
  27971. this.sounds = new Array();
  27972. /**
  27973. * Textures to keep.
  27974. */
  27975. this.textures = new Array();
  27976. }
  27977. return KeepAssets;
  27978. }());
  27979. BABYLON.KeepAssets = KeepAssets;
  27980. /**
  27981. * Container with a set of assets that can be added or removed from a scene.
  27982. */
  27983. var AssetContainer = /** @class */ (function () {
  27984. /**
  27985. * Instantiates an AssetContainer.
  27986. * @param scene The scene the AssetContainer belongs to.
  27987. */
  27988. function AssetContainer(scene) {
  27989. // Objects
  27990. /**
  27991. * Cameras populated in the container.
  27992. */
  27993. this.cameras = new Array();
  27994. /**
  27995. * Lights populated in the container.
  27996. */
  27997. this.lights = new Array();
  27998. /**
  27999. * Meshes populated in the container.
  28000. */
  28001. this.meshes = new Array();
  28002. /**
  28003. * Skeletons populated in the container.
  28004. */
  28005. this.skeletons = new Array();
  28006. /**
  28007. * ParticleSystems populated in the container.
  28008. */
  28009. this.particleSystems = new Array();
  28010. /**
  28011. * Animations populated in the container.
  28012. */
  28013. this.animations = new Array();
  28014. /**
  28015. * AnimationGroups populated in the container.
  28016. */
  28017. this.animationGroups = new Array();
  28018. /**
  28019. * MultiMaterials populated in the container.
  28020. */
  28021. this.multiMaterials = new Array();
  28022. /**
  28023. * Materials populated in the container.
  28024. */
  28025. this.materials = new Array();
  28026. /**
  28027. * MorphTargetManagers populated in the container.
  28028. */
  28029. this.morphTargetManagers = new Array();
  28030. /**
  28031. * Geometries populated in the container.
  28032. */
  28033. this.geometries = new Array();
  28034. /**
  28035. * TransformNodes populated in the container.
  28036. */
  28037. this.transformNodes = new Array();
  28038. /**
  28039. * LensFlareSystems populated in the container.
  28040. */
  28041. this.lensFlareSystems = new Array();
  28042. /**
  28043. * ShadowGenerators populated in the container.
  28044. */
  28045. this.shadowGenerators = new Array();
  28046. /**
  28047. * ActionManagers populated in the container.
  28048. */
  28049. this.actionManagers = new Array();
  28050. /**
  28051. * Sounds populated in the container.
  28052. */
  28053. this.sounds = new Array();
  28054. /**
  28055. * Textures populated in the container.
  28056. */
  28057. this.textures = new Array();
  28058. this.scene = scene;
  28059. }
  28060. /**
  28061. * Adds all the assets from the container to the scene.
  28062. */
  28063. AssetContainer.prototype.addAllToScene = function () {
  28064. var _this = this;
  28065. this.cameras.forEach(function (o) {
  28066. _this.scene.addCamera(o);
  28067. });
  28068. this.lights.forEach(function (o) {
  28069. _this.scene.addLight(o);
  28070. });
  28071. this.meshes.forEach(function (o) {
  28072. _this.scene.addMesh(o);
  28073. });
  28074. this.skeletons.forEach(function (o) {
  28075. _this.scene.addSkeleton(o);
  28076. });
  28077. this.particleSystems.forEach(function (o) {
  28078. _this.scene.addParticleSystem(o);
  28079. });
  28080. this.animations.forEach(function (o) {
  28081. _this.scene.addAnimation(o);
  28082. });
  28083. this.animationGroups.forEach(function (o) {
  28084. _this.scene.addAnimationGroup(o);
  28085. });
  28086. this.multiMaterials.forEach(function (o) {
  28087. _this.scene.addMultiMaterial(o);
  28088. });
  28089. this.materials.forEach(function (o) {
  28090. _this.scene.addMaterial(o);
  28091. });
  28092. this.morphTargetManagers.forEach(function (o) {
  28093. _this.scene.addMorphTargetManager(o);
  28094. });
  28095. this.geometries.forEach(function (o) {
  28096. _this.scene.addGeometry(o);
  28097. });
  28098. this.transformNodes.forEach(function (o) {
  28099. _this.scene.addTransformNode(o);
  28100. });
  28101. this.lensFlareSystems.forEach(function (o) {
  28102. _this.scene.addLensFlareSystem(o);
  28103. });
  28104. this.actionManagers.forEach(function (o) {
  28105. _this.scene.addActionManager(o);
  28106. });
  28107. this.sounds.forEach(function (o) {
  28108. o.play();
  28109. o.autoplay = true;
  28110. _this.scene.mainSoundTrack.AddSound(o);
  28111. });
  28112. this.textures.forEach(function (o) {
  28113. _this.scene.addTexture;
  28114. });
  28115. };
  28116. /**
  28117. * Removes all the assets in the container from the scene
  28118. */
  28119. AssetContainer.prototype.removeAllFromScene = function () {
  28120. var _this = this;
  28121. this.cameras.forEach(function (o) {
  28122. _this.scene.removeCamera(o);
  28123. });
  28124. this.lights.forEach(function (o) {
  28125. _this.scene.removeLight(o);
  28126. });
  28127. this.meshes.forEach(function (o) {
  28128. _this.scene.removeMesh(o);
  28129. });
  28130. this.skeletons.forEach(function (o) {
  28131. _this.scene.removeSkeleton(o);
  28132. });
  28133. this.particleSystems.forEach(function (o) {
  28134. _this.scene.removeParticleSystem(o);
  28135. });
  28136. this.animations.forEach(function (o) {
  28137. _this.scene.removeAnimation(o);
  28138. });
  28139. this.animationGroups.forEach(function (o) {
  28140. _this.scene.removeAnimationGroup(o);
  28141. });
  28142. this.multiMaterials.forEach(function (o) {
  28143. _this.scene.removeMultiMaterial(o);
  28144. });
  28145. this.materials.forEach(function (o) {
  28146. _this.scene.removeMaterial(o);
  28147. });
  28148. this.morphTargetManagers.forEach(function (o) {
  28149. _this.scene.removeMorphTargetManager(o);
  28150. });
  28151. this.geometries.forEach(function (o) {
  28152. _this.scene.removeGeometry(o);
  28153. });
  28154. this.transformNodes.forEach(function (o) {
  28155. _this.scene.removeTransformNode(o);
  28156. });
  28157. this.lensFlareSystems.forEach(function (o) {
  28158. _this.scene.removeLensFlareSystem(o);
  28159. });
  28160. this.actionManagers.forEach(function (o) {
  28161. _this.scene.removeActionManager(o);
  28162. });
  28163. this.sounds.forEach(function (o) {
  28164. o.stop();
  28165. o.autoplay = false;
  28166. _this.scene.mainSoundTrack.RemoveSound(o);
  28167. });
  28168. this.textures.forEach(function (o) {
  28169. _this.scene.removeTexture(o);
  28170. });
  28171. };
  28172. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28173. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28174. var asset = sourceAssets_1[_i];
  28175. var move = true;
  28176. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28177. var keepAsset = keepAssets_1[_a];
  28178. if (asset === keepAsset) {
  28179. move = false;
  28180. break;
  28181. }
  28182. }
  28183. if (move) {
  28184. targetAssets.push(asset);
  28185. }
  28186. }
  28187. };
  28188. /**
  28189. * Removes all the assets contained in the scene and adds them to the container.
  28190. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28191. */
  28192. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28193. if (keepAssets === undefined) {
  28194. keepAssets = new KeepAssets();
  28195. }
  28196. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28197. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28198. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28199. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28200. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28201. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28202. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28203. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28204. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28205. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28206. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28207. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28208. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28209. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28210. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28211. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28212. this.removeAllFromScene();
  28213. };
  28214. return AssetContainer;
  28215. }());
  28216. BABYLON.AssetContainer = AssetContainer;
  28217. })(BABYLON || (BABYLON = {}));
  28218. //# sourceMappingURL=babylon.assetContainer.js.map
  28219. "use strict";
  28220. var BABYLON;
  28221. (function (BABYLON) {
  28222. var Buffer = /** @class */ (function () {
  28223. /**
  28224. * Constructor
  28225. * @param engine the engine
  28226. * @param data the data to use for this buffer
  28227. * @param updatable whether the data is updatable
  28228. * @param stride the stride (optional)
  28229. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28230. * @param instanced whether the buffer is instanced (optional)
  28231. * @param useBytes set to true if the stride in in bytes (optional)
  28232. */
  28233. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28234. if (stride === void 0) { stride = 0; }
  28235. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28236. if (instanced === void 0) { instanced = false; }
  28237. if (useBytes === void 0) { useBytes = false; }
  28238. if (engine instanceof BABYLON.Mesh) {
  28239. this._engine = engine.getScene().getEngine();
  28240. }
  28241. else {
  28242. this._engine = engine;
  28243. }
  28244. this._updatable = updatable;
  28245. this._instanced = instanced;
  28246. this._data = data;
  28247. this.byteStride = useBytes ? stride : stride * 4;
  28248. if (!postponeInternalCreation) {
  28249. this.create();
  28250. }
  28251. }
  28252. /**
  28253. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28254. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28255. * @param offset defines offset in the buffer (0 by default)
  28256. * @param size defines the size in floats of attributes (position is 3 for instance)
  28257. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28258. * @param instanced defines if the vertex buffer contains indexed data
  28259. * @param useBytes defines if the offset and stride are in bytes
  28260. * @returns the new vertex buffer
  28261. */
  28262. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28263. if (useBytes === void 0) { useBytes = false; }
  28264. var byteOffset = useBytes ? offset : offset * 4;
  28265. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  28266. // a lot of these parameters are ignored as they are overriden by the buffer
  28267. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28268. };
  28269. // Properties
  28270. Buffer.prototype.isUpdatable = function () {
  28271. return this._updatable;
  28272. };
  28273. Buffer.prototype.getData = function () {
  28274. return this._data;
  28275. };
  28276. Buffer.prototype.getBuffer = function () {
  28277. return this._buffer;
  28278. };
  28279. /**
  28280. * Gets the stride in float32 units (i.e. byte stride / 4).
  28281. * May not be an integer if the byte stride is not divisible by 4.
  28282. * DEPRECATED. Use byteStride instead.
  28283. * @returns the stride in float32 units
  28284. */
  28285. Buffer.prototype.getStrideSize = function () {
  28286. return this.byteStride / 4;
  28287. };
  28288. // Methods
  28289. Buffer.prototype.create = function (data) {
  28290. if (data === void 0) { data = null; }
  28291. if (!data && this._buffer) {
  28292. return; // nothing to do
  28293. }
  28294. data = data || this._data;
  28295. if (!data) {
  28296. return;
  28297. }
  28298. if (!this._buffer) {
  28299. if (this._updatable) {
  28300. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28301. this._data = data;
  28302. }
  28303. else {
  28304. this._buffer = this._engine.createVertexBuffer(data);
  28305. }
  28306. }
  28307. else if (this._updatable) {
  28308. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28309. this._data = data;
  28310. }
  28311. };
  28312. Buffer.prototype._rebuild = function () {
  28313. this._buffer = null;
  28314. this.create(this._data);
  28315. };
  28316. Buffer.prototype.update = function (data) {
  28317. this.create(data);
  28318. };
  28319. /**
  28320. * Updates the data directly.
  28321. * @param data the new data
  28322. * @param offset the new offset
  28323. * @param vertexCount the vertex count (optional)
  28324. * @param useBytes set to true if the offset is in bytes
  28325. */
  28326. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28327. if (useBytes === void 0) { useBytes = false; }
  28328. if (!this._buffer) {
  28329. return;
  28330. }
  28331. if (this._updatable) {
  28332. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  28333. this._data = null;
  28334. }
  28335. };
  28336. Buffer.prototype.dispose = function () {
  28337. if (!this._buffer) {
  28338. return;
  28339. }
  28340. if (this._engine._releaseBuffer(this._buffer)) {
  28341. this._buffer = null;
  28342. }
  28343. };
  28344. return Buffer;
  28345. }());
  28346. BABYLON.Buffer = Buffer;
  28347. })(BABYLON || (BABYLON = {}));
  28348. //# sourceMappingURL=babylon.buffer.js.map
  28349. "use strict";
  28350. var BABYLON;
  28351. (function (BABYLON) {
  28352. var VertexBuffer = /** @class */ (function () {
  28353. /**
  28354. * Constructor
  28355. * @param engine the engine
  28356. * @param data the data to use for this vertex buffer
  28357. * @param kind the vertex buffer kind
  28358. * @param updatable whether the data is updatable
  28359. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28360. * @param stride the stride (optional)
  28361. * @param instanced whether the buffer is instanced (optional)
  28362. * @param offset the offset of the data (optional)
  28363. * @param size the number of components (optional)
  28364. * @param type the type of the component (optional)
  28365. * @param normalized whether the data contains normalized data (optional)
  28366. * @param useBytes set to true if stride and offset are in bytes (optional)
  28367. */
  28368. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28369. if (normalized === void 0) { normalized = false; }
  28370. if (useBytes === void 0) { useBytes = false; }
  28371. if (data instanceof BABYLON.Buffer) {
  28372. this._buffer = data;
  28373. this._ownsBuffer = false;
  28374. }
  28375. else {
  28376. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28377. this._ownsBuffer = true;
  28378. }
  28379. this._kind = kind;
  28380. if (type == undefined) {
  28381. var data_1 = this.getData();
  28382. this.type = VertexBuffer.FLOAT;
  28383. if (data_1 instanceof Int8Array)
  28384. this.type = VertexBuffer.BYTE;
  28385. else if (data_1 instanceof Uint8Array)
  28386. this.type = VertexBuffer.UNSIGNED_BYTE;
  28387. else if (data_1 instanceof Int16Array)
  28388. this.type = VertexBuffer.SHORT;
  28389. else if (data_1 instanceof Uint16Array)
  28390. this.type = VertexBuffer.UNSIGNED_SHORT;
  28391. else if (data_1 instanceof Int32Array)
  28392. this.type = VertexBuffer.INT;
  28393. else if (data_1 instanceof Uint32Array)
  28394. this.type = VertexBuffer.UNSIGNED_INT;
  28395. }
  28396. else {
  28397. this.type = type;
  28398. }
  28399. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28400. if (useBytes) {
  28401. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28402. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28403. this.byteOffset = offset || 0;
  28404. }
  28405. else {
  28406. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28407. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28408. this.byteOffset = (offset || 0) * typeByteLength;
  28409. }
  28410. this.normalized = normalized;
  28411. this._instanced = instanced !== undefined ? instanced : false;
  28412. this._instanceDivisor = instanced ? 1 : 0;
  28413. }
  28414. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28415. /**
  28416. * Gets or sets the instance divisor when in instanced mode
  28417. */
  28418. get: function () {
  28419. return this._instanceDivisor;
  28420. },
  28421. set: function (value) {
  28422. this._instanceDivisor = value;
  28423. if (value == 0) {
  28424. this._instanced = false;
  28425. }
  28426. else {
  28427. this._instanced = true;
  28428. }
  28429. },
  28430. enumerable: true,
  28431. configurable: true
  28432. });
  28433. VertexBuffer.prototype._rebuild = function () {
  28434. if (!this._buffer) {
  28435. return;
  28436. }
  28437. this._buffer._rebuild();
  28438. };
  28439. /**
  28440. * Returns the kind of the VertexBuffer (string).
  28441. */
  28442. VertexBuffer.prototype.getKind = function () {
  28443. return this._kind;
  28444. };
  28445. // Properties
  28446. /**
  28447. * Boolean : is the VertexBuffer updatable ?
  28448. */
  28449. VertexBuffer.prototype.isUpdatable = function () {
  28450. return this._buffer.isUpdatable();
  28451. };
  28452. /**
  28453. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28454. */
  28455. VertexBuffer.prototype.getData = function () {
  28456. return this._buffer.getData();
  28457. };
  28458. /**
  28459. * Returns the WebGLBuffer associated to the VertexBuffer.
  28460. */
  28461. VertexBuffer.prototype.getBuffer = function () {
  28462. return this._buffer.getBuffer();
  28463. };
  28464. /**
  28465. * Returns the stride as a multiple of the type byte length.
  28466. * DEPRECATED. Use byteStride instead.
  28467. */
  28468. VertexBuffer.prototype.getStrideSize = function () {
  28469. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28470. };
  28471. /**
  28472. * Returns the offset as a multiple of the type byte length.
  28473. * DEPRECATED. Use byteOffset instead.
  28474. */
  28475. VertexBuffer.prototype.getOffset = function () {
  28476. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28477. };
  28478. /**
  28479. * Returns the number of components per vertex attribute (integer).
  28480. */
  28481. VertexBuffer.prototype.getSize = function () {
  28482. return this._size;
  28483. };
  28484. /**
  28485. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28486. */
  28487. VertexBuffer.prototype.getIsInstanced = function () {
  28488. return this._instanced;
  28489. };
  28490. /**
  28491. * Returns the instancing divisor, zero for non-instanced (integer).
  28492. */
  28493. VertexBuffer.prototype.getInstanceDivisor = function () {
  28494. return this._instanceDivisor;
  28495. };
  28496. // Methods
  28497. /**
  28498. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28499. * Returns the created WebGLBuffer.
  28500. */
  28501. VertexBuffer.prototype.create = function (data) {
  28502. return this._buffer.create(data);
  28503. };
  28504. /**
  28505. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28506. * This function will create a new buffer if the current one is not updatable
  28507. * Returns the updated WebGLBuffer.
  28508. */
  28509. VertexBuffer.prototype.update = function (data) {
  28510. return this._buffer.update(data);
  28511. };
  28512. /**
  28513. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28514. * Returns the directly updated WebGLBuffer.
  28515. */
  28516. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  28517. return this._buffer.updateDirectly(data, offset);
  28518. };
  28519. /**
  28520. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28521. */
  28522. VertexBuffer.prototype.dispose = function () {
  28523. if (this._ownsBuffer) {
  28524. this._buffer.dispose();
  28525. }
  28526. };
  28527. /**
  28528. * Enumerates each value of this vertex buffer as numbers.
  28529. * @param count the number of values to enumerate
  28530. * @param callback the callback function called for each value
  28531. */
  28532. VertexBuffer.prototype.forEach = function (count, callback) {
  28533. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28534. };
  28535. Object.defineProperty(VertexBuffer, "PositionKind", {
  28536. get: function () {
  28537. return VertexBuffer._PositionKind;
  28538. },
  28539. enumerable: true,
  28540. configurable: true
  28541. });
  28542. Object.defineProperty(VertexBuffer, "NormalKind", {
  28543. get: function () {
  28544. return VertexBuffer._NormalKind;
  28545. },
  28546. enumerable: true,
  28547. configurable: true
  28548. });
  28549. Object.defineProperty(VertexBuffer, "TangentKind", {
  28550. get: function () {
  28551. return VertexBuffer._TangentKind;
  28552. },
  28553. enumerable: true,
  28554. configurable: true
  28555. });
  28556. Object.defineProperty(VertexBuffer, "UVKind", {
  28557. get: function () {
  28558. return VertexBuffer._UVKind;
  28559. },
  28560. enumerable: true,
  28561. configurable: true
  28562. });
  28563. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28564. get: function () {
  28565. return VertexBuffer._UV2Kind;
  28566. },
  28567. enumerable: true,
  28568. configurable: true
  28569. });
  28570. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28571. get: function () {
  28572. return VertexBuffer._UV3Kind;
  28573. },
  28574. enumerable: true,
  28575. configurable: true
  28576. });
  28577. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28578. get: function () {
  28579. return VertexBuffer._UV4Kind;
  28580. },
  28581. enumerable: true,
  28582. configurable: true
  28583. });
  28584. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28585. get: function () {
  28586. return VertexBuffer._UV5Kind;
  28587. },
  28588. enumerable: true,
  28589. configurable: true
  28590. });
  28591. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28592. get: function () {
  28593. return VertexBuffer._UV6Kind;
  28594. },
  28595. enumerable: true,
  28596. configurable: true
  28597. });
  28598. Object.defineProperty(VertexBuffer, "ColorKind", {
  28599. get: function () {
  28600. return VertexBuffer._ColorKind;
  28601. },
  28602. enumerable: true,
  28603. configurable: true
  28604. });
  28605. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28606. get: function () {
  28607. return VertexBuffer._MatricesIndicesKind;
  28608. },
  28609. enumerable: true,
  28610. configurable: true
  28611. });
  28612. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28613. get: function () {
  28614. return VertexBuffer._MatricesWeightsKind;
  28615. },
  28616. enumerable: true,
  28617. configurable: true
  28618. });
  28619. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28620. get: function () {
  28621. return VertexBuffer._MatricesIndicesExtraKind;
  28622. },
  28623. enumerable: true,
  28624. configurable: true
  28625. });
  28626. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28627. get: function () {
  28628. return VertexBuffer._MatricesWeightsExtraKind;
  28629. },
  28630. enumerable: true,
  28631. configurable: true
  28632. });
  28633. /**
  28634. * Deduces the stride given a kind.
  28635. * @param kind The kind string to deduce
  28636. * @returns The deduced stride
  28637. */
  28638. VertexBuffer.DeduceStride = function (kind) {
  28639. switch (kind) {
  28640. case VertexBuffer.UVKind:
  28641. case VertexBuffer.UV2Kind:
  28642. case VertexBuffer.UV3Kind:
  28643. case VertexBuffer.UV4Kind:
  28644. case VertexBuffer.UV5Kind:
  28645. case VertexBuffer.UV6Kind:
  28646. return 2;
  28647. case VertexBuffer.NormalKind:
  28648. case VertexBuffer.PositionKind:
  28649. return 3;
  28650. case VertexBuffer.ColorKind:
  28651. case VertexBuffer.MatricesIndicesKind:
  28652. case VertexBuffer.MatricesIndicesExtraKind:
  28653. case VertexBuffer.MatricesWeightsKind:
  28654. case VertexBuffer.MatricesWeightsExtraKind:
  28655. case VertexBuffer.TangentKind:
  28656. return 4;
  28657. default:
  28658. throw new Error("Invalid kind '" + kind + "'");
  28659. }
  28660. };
  28661. /**
  28662. * Gets the byte length of the given type.
  28663. * @param type the type
  28664. * @returns the number of bytes
  28665. */
  28666. VertexBuffer.GetTypeByteLength = function (type) {
  28667. switch (type) {
  28668. case VertexBuffer.BYTE:
  28669. case VertexBuffer.UNSIGNED_BYTE:
  28670. return 1;
  28671. case VertexBuffer.SHORT:
  28672. case VertexBuffer.UNSIGNED_SHORT:
  28673. return 2;
  28674. case VertexBuffer.INT:
  28675. case VertexBuffer.FLOAT:
  28676. return 4;
  28677. default:
  28678. throw new Error("Invalid type '" + type + "'");
  28679. }
  28680. };
  28681. /**
  28682. * Enumerates each value of the given parameters as numbers.
  28683. * @param data the data to enumerate
  28684. * @param byteOffset the byte offset of the data
  28685. * @param byteStride the byte stride of the data
  28686. * @param componentCount the number of components per element
  28687. * @param componentType the type of the component
  28688. * @param count the total number of components
  28689. * @param normalized whether the data is normalized
  28690. * @param callback the callback function called for each value
  28691. */
  28692. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  28693. if (data instanceof Array) {
  28694. var offset = byteOffset / 4;
  28695. var stride = byteStride / 4;
  28696. for (var index = 0; index < count; index += componentCount) {
  28697. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28698. callback(data[offset + componentIndex], index + componentIndex);
  28699. }
  28700. offset += stride;
  28701. }
  28702. }
  28703. else {
  28704. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  28705. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  28706. for (var index = 0; index < count; index += componentCount) {
  28707. var componentByteOffset = byteOffset;
  28708. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28709. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  28710. callback(value, index + componentIndex);
  28711. componentByteOffset += componentByteLength;
  28712. }
  28713. byteOffset += byteStride;
  28714. }
  28715. }
  28716. };
  28717. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  28718. switch (type) {
  28719. case VertexBuffer.BYTE: {
  28720. var value = dataView.getInt8(byteOffset);
  28721. if (normalized) {
  28722. value = (value + 0.5) / 127.5;
  28723. }
  28724. return value;
  28725. }
  28726. case VertexBuffer.UNSIGNED_BYTE: {
  28727. var value = dataView.getUint8(byteOffset);
  28728. if (normalized) {
  28729. value = value / 255;
  28730. }
  28731. return value;
  28732. }
  28733. case VertexBuffer.SHORT: {
  28734. var value = dataView.getInt16(byteOffset, true);
  28735. if (normalized) {
  28736. value = (value + 0.5) / 16383.5;
  28737. }
  28738. return value;
  28739. }
  28740. case VertexBuffer.UNSIGNED_SHORT: {
  28741. var value = dataView.getUint16(byteOffset, true);
  28742. if (normalized) {
  28743. value = value / 65535;
  28744. }
  28745. return value;
  28746. }
  28747. case VertexBuffer.FLOAT: {
  28748. return dataView.getFloat32(byteOffset, true);
  28749. }
  28750. default: {
  28751. throw new Error("Invalid component type " + type);
  28752. }
  28753. }
  28754. };
  28755. /**
  28756. * The byte type.
  28757. */
  28758. VertexBuffer.BYTE = 5120;
  28759. /**
  28760. * The unsigned byte type.
  28761. */
  28762. VertexBuffer.UNSIGNED_BYTE = 5121;
  28763. /**
  28764. * The short type.
  28765. */
  28766. VertexBuffer.SHORT = 5122;
  28767. /**
  28768. * The unsigned short type.
  28769. */
  28770. VertexBuffer.UNSIGNED_SHORT = 5123;
  28771. /**
  28772. * The integer type.
  28773. */
  28774. VertexBuffer.INT = 5124;
  28775. /**
  28776. * The unsigned integer type.
  28777. */
  28778. VertexBuffer.UNSIGNED_INT = 5125;
  28779. /**
  28780. * The float type.
  28781. */
  28782. VertexBuffer.FLOAT = 5126;
  28783. // Enums
  28784. VertexBuffer._PositionKind = "position";
  28785. VertexBuffer._NormalKind = "normal";
  28786. VertexBuffer._TangentKind = "tangent";
  28787. VertexBuffer._UVKind = "uv";
  28788. VertexBuffer._UV2Kind = "uv2";
  28789. VertexBuffer._UV3Kind = "uv3";
  28790. VertexBuffer._UV4Kind = "uv4";
  28791. VertexBuffer._UV5Kind = "uv5";
  28792. VertexBuffer._UV6Kind = "uv6";
  28793. VertexBuffer._ColorKind = "color";
  28794. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  28795. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  28796. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  28797. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  28798. return VertexBuffer;
  28799. }());
  28800. BABYLON.VertexBuffer = VertexBuffer;
  28801. })(BABYLON || (BABYLON = {}));
  28802. //# sourceMappingURL=babylon.vertexBuffer.js.map
  28803. "use strict";
  28804. var BABYLON;
  28805. (function (BABYLON) {
  28806. /**
  28807. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  28808. */
  28809. var DummyInternalTextureTracker = /** @class */ (function () {
  28810. function DummyInternalTextureTracker() {
  28811. /**
  28812. * Gets or set the previous tracker in the list
  28813. */
  28814. this.previous = null;
  28815. /**
  28816. * Gets or set the next tracker in the list
  28817. */
  28818. this.next = null;
  28819. }
  28820. return DummyInternalTextureTracker;
  28821. }());
  28822. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  28823. })(BABYLON || (BABYLON = {}));
  28824. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  28825. "use strict";
  28826. var BABYLON;
  28827. (function (BABYLON) {
  28828. /**
  28829. * Class used to store data associated with WebGL texture data for the engine
  28830. * This class should not be used directly
  28831. */
  28832. var InternalTexture = /** @class */ (function () {
  28833. /**
  28834. * Creates a new InternalTexture
  28835. * @param engine defines the engine to use
  28836. * @param dataSource defines the type of data that will be used
  28837. */
  28838. function InternalTexture(engine, dataSource) {
  28839. /**
  28840. * Observable called when the texture is loaded
  28841. */
  28842. this.onLoadedObservable = new BABYLON.Observable();
  28843. /**
  28844. * Gets or set the previous tracker in the list
  28845. */
  28846. this.previous = null;
  28847. /**
  28848. * Gets or set the next tracker in the list
  28849. */
  28850. this.next = null;
  28851. // Private
  28852. /** @ignore */
  28853. this._initialSlot = -1;
  28854. /** @ignore */
  28855. this._designatedSlot = -1;
  28856. /** @ignore */
  28857. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  28858. /** @ignore */
  28859. this._comparisonFunction = 0;
  28860. /** @ignore */
  28861. this._references = 1;
  28862. this._engine = engine;
  28863. this._dataSource = dataSource;
  28864. this._webGLTexture = engine._createTexture();
  28865. }
  28866. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  28867. /**
  28868. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  28869. */
  28870. get: function () {
  28871. return this._dataSource;
  28872. },
  28873. enumerable: true,
  28874. configurable: true
  28875. });
  28876. /**
  28877. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  28878. */
  28879. InternalTexture.prototype.incrementReferences = function () {
  28880. this._references++;
  28881. };
  28882. /**
  28883. * Change the size of the texture (not the size of the content)
  28884. * @param width defines the new width
  28885. * @param height defines the new height
  28886. * @param depth defines the new depth (1 by default)
  28887. */
  28888. InternalTexture.prototype.updateSize = function (width, height, depth) {
  28889. if (depth === void 0) { depth = 1; }
  28890. this.width = width;
  28891. this.height = height;
  28892. this.depth = depth;
  28893. this.baseWidth = width;
  28894. this.baseHeight = height;
  28895. this.baseDepth = depth;
  28896. this._size = width * height * depth;
  28897. };
  28898. /** @ignore */
  28899. InternalTexture.prototype._rebuild = function () {
  28900. var _this = this;
  28901. var proxy;
  28902. this.isReady = false;
  28903. this._cachedCoordinatesMode = null;
  28904. this._cachedWrapU = null;
  28905. this._cachedWrapV = null;
  28906. this._cachedAnisotropicFilteringLevel = null;
  28907. switch (this._dataSource) {
  28908. case InternalTexture.DATASOURCE_TEMP:
  28909. return;
  28910. case InternalTexture.DATASOURCE_URL:
  28911. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  28912. _this.isReady = true;
  28913. }, null, this._buffer, undefined, this.format);
  28914. proxy._swapAndDie(this);
  28915. return;
  28916. case InternalTexture.DATASOURCE_RAW:
  28917. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28918. proxy._swapAndDie(this);
  28919. this.isReady = true;
  28920. return;
  28921. case InternalTexture.DATASOURCE_RAW3D:
  28922. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28923. proxy._swapAndDie(this);
  28924. this.isReady = true;
  28925. return;
  28926. case InternalTexture.DATASOURCE_DYNAMIC:
  28927. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  28928. proxy._swapAndDie(this);
  28929. // The engine will make sure to update content so no need to flag it as isReady = true
  28930. return;
  28931. case InternalTexture.DATASOURCE_RENDERTARGET:
  28932. var options = new BABYLON.RenderTargetCreationOptions();
  28933. options.generateDepthBuffer = this._generateDepthBuffer;
  28934. options.generateMipMaps = this.generateMipMaps;
  28935. options.generateStencilBuffer = this._generateStencilBuffer;
  28936. options.samplingMode = this.samplingMode;
  28937. options.type = this.type;
  28938. if (this.isCube) {
  28939. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  28940. }
  28941. else {
  28942. var size = {
  28943. width: this.width,
  28944. height: this.height
  28945. };
  28946. proxy = this._engine.createRenderTargetTexture(size, options);
  28947. }
  28948. proxy._swapAndDie(this);
  28949. this.isReady = true;
  28950. return;
  28951. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  28952. var depthTextureOptions = {
  28953. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  28954. comparisonFunction: this._comparisonFunction,
  28955. generateStencil: this._generateStencilBuffer,
  28956. isCube: this.isCube
  28957. };
  28958. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  28959. proxy._swapAndDie(this);
  28960. this.isReady = true;
  28961. return;
  28962. case InternalTexture.DATASOURCE_CUBE:
  28963. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  28964. _this.isReady = true;
  28965. }, null, this.format, this._extension);
  28966. proxy._swapAndDie(this);
  28967. return;
  28968. case InternalTexture.DATASOURCE_CUBERAW:
  28969. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28970. proxy._swapAndDie(this);
  28971. this.isReady = true;
  28972. return;
  28973. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  28974. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  28975. if (proxy) {
  28976. proxy._swapAndDie(_this);
  28977. }
  28978. _this.isReady = true;
  28979. }, null, this.format, this._extension);
  28980. return;
  28981. }
  28982. };
  28983. InternalTexture.prototype._swapAndDie = function (target) {
  28984. target._webGLTexture = this._webGLTexture;
  28985. if (this._framebuffer) {
  28986. target._framebuffer = this._framebuffer;
  28987. }
  28988. if (this._depthStencilBuffer) {
  28989. target._depthStencilBuffer = this._depthStencilBuffer;
  28990. }
  28991. if (this._lodTextureHigh) {
  28992. if (target._lodTextureHigh) {
  28993. target._lodTextureHigh.dispose();
  28994. }
  28995. target._lodTextureHigh = this._lodTextureHigh;
  28996. }
  28997. if (this._lodTextureMid) {
  28998. if (target._lodTextureMid) {
  28999. target._lodTextureMid.dispose();
  29000. }
  29001. target._lodTextureMid = this._lodTextureMid;
  29002. }
  29003. if (this._lodTextureLow) {
  29004. if (target._lodTextureLow) {
  29005. target._lodTextureLow.dispose();
  29006. }
  29007. target._lodTextureLow = this._lodTextureLow;
  29008. }
  29009. var cache = this._engine.getLoadedTexturesCache();
  29010. var index = cache.indexOf(this);
  29011. if (index !== -1) {
  29012. cache.splice(index, 1);
  29013. }
  29014. };
  29015. /**
  29016. * Dispose the current allocated resources
  29017. */
  29018. InternalTexture.prototype.dispose = function () {
  29019. if (!this._webGLTexture) {
  29020. return;
  29021. }
  29022. this._references--;
  29023. if (this._references === 0) {
  29024. this._engine._releaseTexture(this);
  29025. this._webGLTexture = null;
  29026. this.previous = null;
  29027. this.next = null;
  29028. }
  29029. };
  29030. /**
  29031. * The source of the texture data is unknown
  29032. */
  29033. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29034. /**
  29035. * Texture data comes from an URL
  29036. */
  29037. InternalTexture.DATASOURCE_URL = 1;
  29038. /**
  29039. * Texture data is only used for temporary storage
  29040. */
  29041. InternalTexture.DATASOURCE_TEMP = 2;
  29042. /**
  29043. * Texture data comes from raw data (ArrayBuffer)
  29044. */
  29045. InternalTexture.DATASOURCE_RAW = 3;
  29046. /**
  29047. * Texture content is dynamic (video or dynamic texture)
  29048. */
  29049. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29050. /**
  29051. * Texture content is generated by rendering to it
  29052. */
  29053. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29054. /**
  29055. * Texture content is part of a multi render target process
  29056. */
  29057. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29058. /**
  29059. * Texture data comes from a cube data file
  29060. */
  29061. InternalTexture.DATASOURCE_CUBE = 7;
  29062. /**
  29063. * Texture data comes from a raw cube data
  29064. */
  29065. InternalTexture.DATASOURCE_CUBERAW = 8;
  29066. /**
  29067. * Texture data come from a prefiltered cube data file
  29068. */
  29069. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29070. /**
  29071. * Texture content is raw 3D data
  29072. */
  29073. InternalTexture.DATASOURCE_RAW3D = 10;
  29074. /**
  29075. * Texture content is a depth texture
  29076. */
  29077. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29078. return InternalTexture;
  29079. }());
  29080. BABYLON.InternalTexture = InternalTexture;
  29081. })(BABYLON || (BABYLON = {}));
  29082. //# sourceMappingURL=babylon.internalTexture.js.map
  29083. "use strict";
  29084. var BABYLON;
  29085. (function (BABYLON) {
  29086. var BaseTexture = /** @class */ (function () {
  29087. function BaseTexture(scene) {
  29088. this._hasAlpha = false;
  29089. this.getAlphaFromRGB = false;
  29090. this.level = 1;
  29091. this.coordinatesIndex = 0;
  29092. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29093. /**
  29094. * | Value | Type | Description |
  29095. * | ----- | ------------------ | ----------- |
  29096. * | 0 | CLAMP_ADDRESSMODE | |
  29097. * | 1 | WRAP_ADDRESSMODE | |
  29098. * | 2 | MIRROR_ADDRESSMODE | |
  29099. */
  29100. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29101. /**
  29102. * | Value | Type | Description |
  29103. * | ----- | ------------------ | ----------- |
  29104. * | 0 | CLAMP_ADDRESSMODE | |
  29105. * | 1 | WRAP_ADDRESSMODE | |
  29106. * | 2 | MIRROR_ADDRESSMODE | |
  29107. */
  29108. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29109. /**
  29110. * | Value | Type | Description |
  29111. * | ----- | ------------------ | ----------- |
  29112. * | 0 | CLAMP_ADDRESSMODE | |
  29113. * | 1 | WRAP_ADDRESSMODE | |
  29114. * | 2 | MIRROR_ADDRESSMODE | |
  29115. */
  29116. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29117. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29118. this.isCube = false;
  29119. this.is3D = false;
  29120. this.gammaSpace = true;
  29121. this.invertZ = false;
  29122. this.lodLevelInAlpha = false;
  29123. this.lodGenerationOffset = 0.0;
  29124. this.lodGenerationScale = 0.8;
  29125. this.isRenderTarget = false;
  29126. this.animations = new Array();
  29127. /**
  29128. * An event triggered when the texture is disposed.
  29129. */
  29130. this.onDisposeObservable = new BABYLON.Observable();
  29131. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29132. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29133. if (this._scene) {
  29134. this._scene.textures.push(this);
  29135. }
  29136. this._uid = null;
  29137. }
  29138. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29139. get: function () {
  29140. return this._hasAlpha;
  29141. },
  29142. set: function (value) {
  29143. if (this._hasAlpha === value) {
  29144. return;
  29145. }
  29146. this._hasAlpha = value;
  29147. if (this._scene) {
  29148. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29149. }
  29150. },
  29151. enumerable: true,
  29152. configurable: true
  29153. });
  29154. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29155. get: function () {
  29156. return this._coordinatesMode;
  29157. },
  29158. /**
  29159. * How a texture is mapped.
  29160. *
  29161. * | Value | Type | Description |
  29162. * | ----- | ----------------------------------- | ----------- |
  29163. * | 0 | EXPLICIT_MODE | |
  29164. * | 1 | SPHERICAL_MODE | |
  29165. * | 2 | PLANAR_MODE | |
  29166. * | 3 | CUBIC_MODE | |
  29167. * | 4 | PROJECTION_MODE | |
  29168. * | 5 | SKYBOX_MODE | |
  29169. * | 6 | INVCUBIC_MODE | |
  29170. * | 7 | EQUIRECTANGULAR_MODE | |
  29171. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29172. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29173. */
  29174. set: function (value) {
  29175. if (this._coordinatesMode === value) {
  29176. return;
  29177. }
  29178. this._coordinatesMode = value;
  29179. if (this._scene) {
  29180. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29181. }
  29182. },
  29183. enumerable: true,
  29184. configurable: true
  29185. });
  29186. Object.defineProperty(BaseTexture.prototype, "uid", {
  29187. get: function () {
  29188. if (!this._uid) {
  29189. this._uid = BABYLON.Tools.RandomId();
  29190. }
  29191. return this._uid;
  29192. },
  29193. enumerable: true,
  29194. configurable: true
  29195. });
  29196. BaseTexture.prototype.toString = function () {
  29197. return this.name;
  29198. };
  29199. BaseTexture.prototype.getClassName = function () {
  29200. return "BaseTexture";
  29201. };
  29202. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29203. set: function (callback) {
  29204. if (this._onDisposeObserver) {
  29205. this.onDisposeObservable.remove(this._onDisposeObserver);
  29206. }
  29207. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29208. },
  29209. enumerable: true,
  29210. configurable: true
  29211. });
  29212. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29213. get: function () {
  29214. return true;
  29215. },
  29216. enumerable: true,
  29217. configurable: true
  29218. });
  29219. BaseTexture.prototype.getScene = function () {
  29220. return this._scene;
  29221. };
  29222. BaseTexture.prototype.getTextureMatrix = function () {
  29223. return BABYLON.Matrix.IdentityReadOnly;
  29224. };
  29225. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29226. return BABYLON.Matrix.IdentityReadOnly;
  29227. };
  29228. BaseTexture.prototype.getInternalTexture = function () {
  29229. return this._texture;
  29230. };
  29231. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29232. return !this.isBlocking || this.isReady();
  29233. };
  29234. BaseTexture.prototype.isReady = function () {
  29235. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29236. this.delayLoad();
  29237. return false;
  29238. }
  29239. if (this._texture) {
  29240. return this._texture.isReady;
  29241. }
  29242. return false;
  29243. };
  29244. BaseTexture.prototype.getSize = function () {
  29245. if (this._texture && this._texture.width) {
  29246. return new BABYLON.Size(this._texture.width, this._texture.height);
  29247. }
  29248. if (this._texture && this._texture._size) {
  29249. return new BABYLON.Size(this._texture._size, this._texture._size);
  29250. }
  29251. return BABYLON.Size.Zero();
  29252. };
  29253. BaseTexture.prototype.getBaseSize = function () {
  29254. if (!this.isReady() || !this._texture)
  29255. return BABYLON.Size.Zero();
  29256. if (this._texture._size) {
  29257. return new BABYLON.Size(this._texture._size, this._texture._size);
  29258. }
  29259. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29260. };
  29261. BaseTexture.prototype.scale = function (ratio) {
  29262. };
  29263. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29264. get: function () {
  29265. return false;
  29266. },
  29267. enumerable: true,
  29268. configurable: true
  29269. });
  29270. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29271. if (!this._scene) {
  29272. return null;
  29273. }
  29274. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29275. for (var index = 0; index < texturesCache.length; index++) {
  29276. var texturesCacheEntry = texturesCache[index];
  29277. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29278. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29279. texturesCacheEntry.incrementReferences();
  29280. return texturesCacheEntry;
  29281. }
  29282. }
  29283. }
  29284. return null;
  29285. };
  29286. BaseTexture.prototype._rebuild = function () {
  29287. };
  29288. BaseTexture.prototype.delayLoad = function () {
  29289. };
  29290. BaseTexture.prototype.clone = function () {
  29291. return null;
  29292. };
  29293. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29294. get: function () {
  29295. if (!this._texture) {
  29296. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29297. }
  29298. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29304. get: function () {
  29305. if (!this._texture) {
  29306. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29307. }
  29308. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29309. },
  29310. enumerable: true,
  29311. configurable: true
  29312. });
  29313. BaseTexture.prototype.readPixels = function (faceIndex) {
  29314. if (faceIndex === void 0) { faceIndex = 0; }
  29315. if (!this._texture) {
  29316. return null;
  29317. }
  29318. var size = this.getSize();
  29319. var scene = this.getScene();
  29320. if (!scene) {
  29321. return null;
  29322. }
  29323. var engine = scene.getEngine();
  29324. if (this._texture.isCube) {
  29325. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29326. }
  29327. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29328. };
  29329. BaseTexture.prototype.releaseInternalTexture = function () {
  29330. if (this._texture) {
  29331. this._texture.dispose();
  29332. this._texture = null;
  29333. }
  29334. };
  29335. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29336. get: function () {
  29337. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29338. return null;
  29339. }
  29340. if (!this._texture._sphericalPolynomial) {
  29341. this._texture._sphericalPolynomial =
  29342. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29343. }
  29344. return this._texture._sphericalPolynomial;
  29345. },
  29346. set: function (value) {
  29347. if (this._texture) {
  29348. this._texture._sphericalPolynomial = value;
  29349. }
  29350. },
  29351. enumerable: true,
  29352. configurable: true
  29353. });
  29354. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29355. get: function () {
  29356. if (this._texture) {
  29357. return this._texture._lodTextureHigh;
  29358. }
  29359. return null;
  29360. },
  29361. enumerable: true,
  29362. configurable: true
  29363. });
  29364. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29365. get: function () {
  29366. if (this._texture) {
  29367. return this._texture._lodTextureMid;
  29368. }
  29369. return null;
  29370. },
  29371. enumerable: true,
  29372. configurable: true
  29373. });
  29374. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29375. get: function () {
  29376. if (this._texture) {
  29377. return this._texture._lodTextureLow;
  29378. }
  29379. return null;
  29380. },
  29381. enumerable: true,
  29382. configurable: true
  29383. });
  29384. BaseTexture.prototype.dispose = function () {
  29385. if (!this._scene) {
  29386. return;
  29387. }
  29388. // Animations
  29389. this._scene.stopAnimation(this);
  29390. // Remove from scene
  29391. this._scene._removePendingData(this);
  29392. var index = this._scene.textures.indexOf(this);
  29393. if (index >= 0) {
  29394. this._scene.textures.splice(index, 1);
  29395. }
  29396. if (this._texture === undefined) {
  29397. return;
  29398. }
  29399. // Release
  29400. this.releaseInternalTexture();
  29401. // Callback
  29402. this.onDisposeObservable.notifyObservers(this);
  29403. this.onDisposeObservable.clear();
  29404. };
  29405. BaseTexture.prototype.serialize = function () {
  29406. if (!this.name) {
  29407. return null;
  29408. }
  29409. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29410. // Animations
  29411. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29412. return serializationObject;
  29413. };
  29414. BaseTexture.WhenAllReady = function (textures, callback) {
  29415. var numRemaining = textures.length;
  29416. if (numRemaining === 0) {
  29417. callback();
  29418. return;
  29419. }
  29420. var _loop_1 = function () {
  29421. texture = textures[i];
  29422. if (texture.isReady()) {
  29423. if (--numRemaining === 0) {
  29424. callback();
  29425. }
  29426. }
  29427. else {
  29428. onLoadObservable = texture.onLoadObservable;
  29429. var onLoadCallback_1 = function () {
  29430. onLoadObservable.removeCallback(onLoadCallback_1);
  29431. if (--numRemaining === 0) {
  29432. callback();
  29433. }
  29434. };
  29435. onLoadObservable.add(onLoadCallback_1);
  29436. }
  29437. };
  29438. var texture, onLoadObservable;
  29439. for (var i = 0; i < textures.length; i++) {
  29440. _loop_1();
  29441. }
  29442. };
  29443. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29444. __decorate([
  29445. BABYLON.serialize()
  29446. ], BaseTexture.prototype, "name", void 0);
  29447. __decorate([
  29448. BABYLON.serialize("hasAlpha")
  29449. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29450. __decorate([
  29451. BABYLON.serialize()
  29452. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29453. __decorate([
  29454. BABYLON.serialize()
  29455. ], BaseTexture.prototype, "level", void 0);
  29456. __decorate([
  29457. BABYLON.serialize()
  29458. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29459. __decorate([
  29460. BABYLON.serialize("coordinatesMode")
  29461. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29462. __decorate([
  29463. BABYLON.serialize()
  29464. ], BaseTexture.prototype, "wrapU", void 0);
  29465. __decorate([
  29466. BABYLON.serialize()
  29467. ], BaseTexture.prototype, "wrapV", void 0);
  29468. __decorate([
  29469. BABYLON.serialize()
  29470. ], BaseTexture.prototype, "wrapR", void 0);
  29471. __decorate([
  29472. BABYLON.serialize()
  29473. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29474. __decorate([
  29475. BABYLON.serialize()
  29476. ], BaseTexture.prototype, "isCube", void 0);
  29477. __decorate([
  29478. BABYLON.serialize()
  29479. ], BaseTexture.prototype, "is3D", void 0);
  29480. __decorate([
  29481. BABYLON.serialize()
  29482. ], BaseTexture.prototype, "gammaSpace", void 0);
  29483. __decorate([
  29484. BABYLON.serialize()
  29485. ], BaseTexture.prototype, "invertZ", void 0);
  29486. __decorate([
  29487. BABYLON.serialize()
  29488. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29489. __decorate([
  29490. BABYLON.serialize()
  29491. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29492. __decorate([
  29493. BABYLON.serialize()
  29494. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29495. __decorate([
  29496. BABYLON.serialize()
  29497. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29498. return BaseTexture;
  29499. }());
  29500. BABYLON.BaseTexture = BaseTexture;
  29501. })(BABYLON || (BABYLON = {}));
  29502. //# sourceMappingURL=babylon.baseTexture.js.map
  29503. "use strict";
  29504. var BABYLON;
  29505. (function (BABYLON) {
  29506. var Texture = /** @class */ (function (_super) {
  29507. __extends(Texture, _super);
  29508. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29509. if (noMipmap === void 0) { noMipmap = false; }
  29510. if (invertY === void 0) { invertY = true; }
  29511. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29512. if (onLoad === void 0) { onLoad = null; }
  29513. if (onError === void 0) { onError = null; }
  29514. if (buffer === void 0) { buffer = null; }
  29515. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29516. var _this = _super.call(this, scene) || this;
  29517. _this.uOffset = 0;
  29518. _this.vOffset = 0;
  29519. _this.uScale = 1.0;
  29520. _this.vScale = 1.0;
  29521. _this.uAng = 0;
  29522. _this.vAng = 0;
  29523. _this.wAng = 0;
  29524. _this._isBlocking = true;
  29525. _this.name = url || "";
  29526. _this.url = url;
  29527. _this._noMipmap = noMipmap;
  29528. _this._invertY = invertY;
  29529. _this._samplingMode = samplingMode;
  29530. _this._buffer = buffer;
  29531. _this._deleteBuffer = deleteBuffer;
  29532. if (format) {
  29533. _this._format = format;
  29534. }
  29535. scene = _this.getScene();
  29536. if (!scene) {
  29537. return _this;
  29538. }
  29539. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29540. var load = function () {
  29541. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29542. _this.onLoadObservable.notifyObservers(_this);
  29543. }
  29544. if (onLoad) {
  29545. onLoad();
  29546. }
  29547. if (!_this.isBlocking && scene) {
  29548. scene.resetCachedMaterial();
  29549. }
  29550. };
  29551. if (!_this.url) {
  29552. _this._delayedOnLoad = load;
  29553. _this._delayedOnError = onError;
  29554. return _this;
  29555. }
  29556. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29557. if (!_this._texture) {
  29558. if (!scene.useDelayedTextureLoading) {
  29559. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29560. if (deleteBuffer) {
  29561. delete _this._buffer;
  29562. }
  29563. }
  29564. else {
  29565. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29566. _this._delayedOnLoad = load;
  29567. _this._delayedOnError = onError;
  29568. }
  29569. }
  29570. else {
  29571. if (_this._texture.isReady) {
  29572. BABYLON.Tools.SetImmediate(function () { return load(); });
  29573. }
  29574. else {
  29575. _this._texture.onLoadedObservable.add(load);
  29576. }
  29577. }
  29578. return _this;
  29579. }
  29580. Object.defineProperty(Texture.prototype, "noMipmap", {
  29581. get: function () {
  29582. return this._noMipmap;
  29583. },
  29584. enumerable: true,
  29585. configurable: true
  29586. });
  29587. Object.defineProperty(Texture.prototype, "isBlocking", {
  29588. get: function () {
  29589. return this._isBlocking;
  29590. },
  29591. set: function (value) {
  29592. this._isBlocking = value;
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(Texture.prototype, "samplingMode", {
  29598. get: function () {
  29599. return this._samplingMode;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. Texture.prototype.updateURL = function (url) {
  29605. this.url = url;
  29606. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29607. this.delayLoad();
  29608. };
  29609. Texture.prototype.delayLoad = function () {
  29610. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29611. return;
  29612. }
  29613. var scene = this.getScene();
  29614. if (!scene) {
  29615. return;
  29616. }
  29617. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29618. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29619. if (!this._texture) {
  29620. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29621. if (this._deleteBuffer) {
  29622. delete this._buffer;
  29623. }
  29624. }
  29625. else {
  29626. if (this._delayedOnLoad) {
  29627. if (this._texture.isReady) {
  29628. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29629. }
  29630. else {
  29631. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29632. }
  29633. }
  29634. }
  29635. this._delayedOnLoad = null;
  29636. this._delayedOnError = null;
  29637. };
  29638. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29639. if (!this._texture) {
  29640. return;
  29641. }
  29642. var scene = this.getScene();
  29643. if (!scene) {
  29644. return;
  29645. }
  29646. this._samplingMode = samplingMode;
  29647. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29648. };
  29649. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29650. x *= this.uScale;
  29651. y *= this.vScale;
  29652. x -= 0.5 * this.uScale;
  29653. y -= 0.5 * this.vScale;
  29654. z -= 0.5;
  29655. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  29656. t.x += 0.5 * this.uScale + this.uOffset;
  29657. t.y += 0.5 * this.vScale + this.vOffset;
  29658. t.z += 0.5;
  29659. };
  29660. Texture.prototype.getTextureMatrix = function () {
  29661. var _this = this;
  29662. if (this.uOffset === this._cachedUOffset &&
  29663. this.vOffset === this._cachedVOffset &&
  29664. this.uScale === this._cachedUScale &&
  29665. this.vScale === this._cachedVScale &&
  29666. this.uAng === this._cachedUAng &&
  29667. this.vAng === this._cachedVAng &&
  29668. this.wAng === this._cachedWAng) {
  29669. return this._cachedTextureMatrix;
  29670. }
  29671. this._cachedUOffset = this.uOffset;
  29672. this._cachedVOffset = this.vOffset;
  29673. this._cachedUScale = this.uScale;
  29674. this._cachedVScale = this.vScale;
  29675. this._cachedUAng = this.uAng;
  29676. this._cachedVAng = this.vAng;
  29677. this._cachedWAng = this.wAng;
  29678. if (!this._cachedTextureMatrix) {
  29679. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29680. this._rowGenerationMatrix = new BABYLON.Matrix();
  29681. this._t0 = BABYLON.Vector3.Zero();
  29682. this._t1 = BABYLON.Vector3.Zero();
  29683. this._t2 = BABYLON.Vector3.Zero();
  29684. }
  29685. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  29686. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  29687. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  29688. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  29689. this._t1.subtractInPlace(this._t0);
  29690. this._t2.subtractInPlace(this._t0);
  29691. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29692. this._cachedTextureMatrix.m[0] = this._t1.x;
  29693. this._cachedTextureMatrix.m[1] = this._t1.y;
  29694. this._cachedTextureMatrix.m[2] = this._t1.z;
  29695. this._cachedTextureMatrix.m[4] = this._t2.x;
  29696. this._cachedTextureMatrix.m[5] = this._t2.y;
  29697. this._cachedTextureMatrix.m[6] = this._t2.z;
  29698. this._cachedTextureMatrix.m[8] = this._t0.x;
  29699. this._cachedTextureMatrix.m[9] = this._t0.y;
  29700. this._cachedTextureMatrix.m[10] = this._t0.z;
  29701. var scene = this.getScene();
  29702. if (!scene) {
  29703. return this._cachedTextureMatrix;
  29704. }
  29705. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29706. return mat.hasTexture(_this);
  29707. });
  29708. return this._cachedTextureMatrix;
  29709. };
  29710. Texture.prototype.getReflectionTextureMatrix = function () {
  29711. var _this = this;
  29712. var scene = this.getScene();
  29713. if (!scene) {
  29714. return this._cachedTextureMatrix;
  29715. }
  29716. if (this.uOffset === this._cachedUOffset &&
  29717. this.vOffset === this._cachedVOffset &&
  29718. this.uScale === this._cachedUScale &&
  29719. this.vScale === this._cachedVScale &&
  29720. this.coordinatesMode === this._cachedCoordinatesMode) {
  29721. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  29722. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  29723. return this._cachedTextureMatrix;
  29724. }
  29725. }
  29726. else {
  29727. return this._cachedTextureMatrix;
  29728. }
  29729. }
  29730. if (!this._cachedTextureMatrix) {
  29731. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29732. }
  29733. if (!this._projectionModeMatrix) {
  29734. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  29735. }
  29736. this._cachedUOffset = this.uOffset;
  29737. this._cachedVOffset = this.vOffset;
  29738. this._cachedUScale = this.uScale;
  29739. this._cachedVScale = this.vScale;
  29740. this._cachedCoordinatesMode = this.coordinatesMode;
  29741. switch (this.coordinatesMode) {
  29742. case Texture.PLANAR_MODE:
  29743. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29744. this._cachedTextureMatrix[0] = this.uScale;
  29745. this._cachedTextureMatrix[5] = this.vScale;
  29746. this._cachedTextureMatrix[12] = this.uOffset;
  29747. this._cachedTextureMatrix[13] = this.vOffset;
  29748. break;
  29749. case Texture.PROJECTION_MODE:
  29750. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  29751. this._projectionModeMatrix.m[0] = 0.5;
  29752. this._projectionModeMatrix.m[5] = -0.5;
  29753. this._projectionModeMatrix.m[10] = 0.0;
  29754. this._projectionModeMatrix.m[12] = 0.5;
  29755. this._projectionModeMatrix.m[13] = 0.5;
  29756. this._projectionModeMatrix.m[14] = 1.0;
  29757. this._projectionModeMatrix.m[15] = 1.0;
  29758. var projectionMatrix = scene.getProjectionMatrix();
  29759. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  29760. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  29761. break;
  29762. default:
  29763. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29764. break;
  29765. }
  29766. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29767. return (mat.getActiveTextures().indexOf(_this) !== -1);
  29768. });
  29769. return this._cachedTextureMatrix;
  29770. };
  29771. Texture.prototype.clone = function () {
  29772. var _this = this;
  29773. return BABYLON.SerializationHelper.Clone(function () {
  29774. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  29775. }, this);
  29776. };
  29777. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  29778. get: function () {
  29779. if (!this._onLoadObservable) {
  29780. this._onLoadObservable = new BABYLON.Observable();
  29781. }
  29782. return this._onLoadObservable;
  29783. },
  29784. enumerable: true,
  29785. configurable: true
  29786. });
  29787. Texture.prototype.serialize = function () {
  29788. var serializationObject = _super.prototype.serialize.call(this);
  29789. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  29790. serializationObject.base64String = this._buffer;
  29791. serializationObject.name = serializationObject.name.replace("data:", "");
  29792. }
  29793. return serializationObject;
  29794. };
  29795. Texture.prototype.getClassName = function () {
  29796. return "Texture";
  29797. };
  29798. Texture.prototype.dispose = function () {
  29799. _super.prototype.dispose.call(this);
  29800. if (this.onLoadObservable) {
  29801. this.onLoadObservable.clear();
  29802. this._onLoadObservable = null;
  29803. }
  29804. this._delayedOnLoad = null;
  29805. this._delayedOnError = null;
  29806. };
  29807. // Statics
  29808. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  29809. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29810. if (onLoad === void 0) { onLoad = null; }
  29811. if (onError === void 0) { onError = null; }
  29812. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29813. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  29814. };
  29815. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  29816. if (parsedTexture.customType) {
  29817. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  29818. // Update Sampling Mode
  29819. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  29820. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  29821. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  29822. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  29823. }
  29824. }
  29825. return parsedCustomTexture;
  29826. }
  29827. if (parsedTexture.isCube) {
  29828. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  29829. }
  29830. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  29831. return null;
  29832. }
  29833. var texture = BABYLON.SerializationHelper.Parse(function () {
  29834. var generateMipMaps = true;
  29835. if (parsedTexture.noMipmap) {
  29836. generateMipMaps = false;
  29837. }
  29838. if (parsedTexture.mirrorPlane) {
  29839. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  29840. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  29841. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  29842. return mirrorTexture;
  29843. }
  29844. else if (parsedTexture.isRenderTarget) {
  29845. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  29846. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  29847. return renderTargetTexture;
  29848. }
  29849. else {
  29850. var texture;
  29851. if (parsedTexture.base64String) {
  29852. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  29853. }
  29854. else {
  29855. var url = rootUrl + parsedTexture.name;
  29856. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  29857. url = parsedTexture.url;
  29858. }
  29859. texture = new Texture(url, scene, !generateMipMaps);
  29860. }
  29861. return texture;
  29862. }
  29863. }, parsedTexture, scene);
  29864. // Update Sampling Mode
  29865. if (parsedTexture.samplingMode) {
  29866. var sampling = parsedTexture.samplingMode;
  29867. if (texture._samplingMode !== sampling) {
  29868. texture.updateSamplingMode(sampling);
  29869. }
  29870. }
  29871. // Animations
  29872. if (parsedTexture.animations) {
  29873. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  29874. var parsedAnimation = parsedTexture.animations[animationIndex];
  29875. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29876. }
  29877. }
  29878. return texture;
  29879. };
  29880. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  29881. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29882. if (noMipmap === void 0) { noMipmap = false; }
  29883. if (invertY === void 0) { invertY = true; }
  29884. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29885. if (onLoad === void 0) { onLoad = null; }
  29886. if (onError === void 0) { onError = null; }
  29887. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29888. if (name.substr(0, 5) !== "data:") {
  29889. name = "data:" + name;
  29890. }
  29891. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  29892. };
  29893. // Constants
  29894. Texture.NEAREST_SAMPLINGMODE = 1;
  29895. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  29896. Texture.BILINEAR_SAMPLINGMODE = 2;
  29897. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  29898. Texture.TRILINEAR_SAMPLINGMODE = 3;
  29899. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  29900. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  29901. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  29902. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  29903. Texture.NEAREST_LINEAR = 7;
  29904. Texture.NEAREST_NEAREST = 8;
  29905. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  29906. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  29907. Texture.LINEAR_LINEAR = 11;
  29908. Texture.LINEAR_NEAREST = 12;
  29909. Texture.EXPLICIT_MODE = 0;
  29910. Texture.SPHERICAL_MODE = 1;
  29911. Texture.PLANAR_MODE = 2;
  29912. Texture.CUBIC_MODE = 3;
  29913. Texture.PROJECTION_MODE = 4;
  29914. Texture.SKYBOX_MODE = 5;
  29915. Texture.INVCUBIC_MODE = 6;
  29916. Texture.EQUIRECTANGULAR_MODE = 7;
  29917. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  29918. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  29919. Texture.CLAMP_ADDRESSMODE = 0;
  29920. Texture.WRAP_ADDRESSMODE = 1;
  29921. Texture.MIRROR_ADDRESSMODE = 2;
  29922. /**
  29923. * 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
  29924. */
  29925. Texture.UseSerializedUrlIfAny = false;
  29926. __decorate([
  29927. BABYLON.serialize()
  29928. ], Texture.prototype, "url", void 0);
  29929. __decorate([
  29930. BABYLON.serialize()
  29931. ], Texture.prototype, "uOffset", void 0);
  29932. __decorate([
  29933. BABYLON.serialize()
  29934. ], Texture.prototype, "vOffset", void 0);
  29935. __decorate([
  29936. BABYLON.serialize()
  29937. ], Texture.prototype, "uScale", void 0);
  29938. __decorate([
  29939. BABYLON.serialize()
  29940. ], Texture.prototype, "vScale", void 0);
  29941. __decorate([
  29942. BABYLON.serialize()
  29943. ], Texture.prototype, "uAng", void 0);
  29944. __decorate([
  29945. BABYLON.serialize()
  29946. ], Texture.prototype, "vAng", void 0);
  29947. __decorate([
  29948. BABYLON.serialize()
  29949. ], Texture.prototype, "wAng", void 0);
  29950. __decorate([
  29951. BABYLON.serialize()
  29952. ], Texture.prototype, "isBlocking", null);
  29953. return Texture;
  29954. }(BABYLON.BaseTexture));
  29955. BABYLON.Texture = Texture;
  29956. })(BABYLON || (BABYLON = {}));
  29957. //# sourceMappingURL=babylon.texture.js.map
  29958. "use strict";
  29959. var BABYLON;
  29960. (function (BABYLON) {
  29961. var _InstancesBatch = /** @class */ (function () {
  29962. function _InstancesBatch() {
  29963. this.mustReturn = false;
  29964. this.visibleInstances = new Array();
  29965. this.renderSelf = new Array();
  29966. }
  29967. return _InstancesBatch;
  29968. }());
  29969. BABYLON._InstancesBatch = _InstancesBatch;
  29970. var Mesh = /** @class */ (function (_super) {
  29971. __extends(Mesh, _super);
  29972. /**
  29973. * @constructor
  29974. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  29975. * @param {Scene} scene The scene to add this mesh to.
  29976. * @param {Node} parent The parent of this mesh, if it has one
  29977. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  29978. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  29979. * When false, achieved by calling a clone(), also passing False.
  29980. * This will make creation of children, recursive.
  29981. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  29982. */
  29983. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  29984. if (scene === void 0) { scene = null; }
  29985. if (parent === void 0) { parent = null; }
  29986. if (source === void 0) { source = null; }
  29987. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29988. var _this = _super.call(this, name, scene) || this;
  29989. // Events
  29990. /**
  29991. * An event triggered before rendering the mesh
  29992. */
  29993. _this.onBeforeRenderObservable = new BABYLON.Observable();
  29994. /**
  29995. * An event triggered after rendering the mesh
  29996. */
  29997. _this.onAfterRenderObservable = new BABYLON.Observable();
  29998. /**
  29999. * An event triggered before drawing the mesh
  30000. */
  30001. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30002. // Members
  30003. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30004. _this.instances = new Array();
  30005. _this._LODLevels = new Array();
  30006. _this._visibleInstances = {};
  30007. _this._renderIdForInstances = new Array();
  30008. _this._batchCache = new _InstancesBatch();
  30009. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30010. // Use by builder only to know what orientation were the mesh build in.
  30011. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30012. _this.overrideMaterialSideOrientation = null;
  30013. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30014. // Will be used to save a source mesh reference, If any
  30015. _this._source = null;
  30016. scene = _this.getScene();
  30017. if (source) {
  30018. // Source mesh
  30019. _this._source = source;
  30020. // Geometry
  30021. if (source._geometry) {
  30022. source._geometry.applyToMesh(_this);
  30023. }
  30024. // Deep copy
  30025. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30026. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30027. // Metadata
  30028. if (source.metadata && source.metadata.clone) {
  30029. _this.metadata = source.metadata.clone();
  30030. }
  30031. else {
  30032. _this.metadata = source.metadata;
  30033. }
  30034. // Tags
  30035. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30036. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30037. }
  30038. // Parent
  30039. _this.parent = source.parent;
  30040. // Pivot
  30041. _this.setPivotMatrix(source.getPivotMatrix());
  30042. _this.id = name + "." + source.id;
  30043. // Material
  30044. _this.material = source.material;
  30045. var index;
  30046. if (!doNotCloneChildren) {
  30047. // Children
  30048. var directDescendants = source.getDescendants(true);
  30049. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30050. var child = directDescendants[index_1];
  30051. if (child.clone) {
  30052. child.clone(name + "." + child.name, _this);
  30053. }
  30054. }
  30055. }
  30056. // Physics clone
  30057. var physicsEngine = _this.getScene().getPhysicsEngine();
  30058. if (clonePhysicsImpostor && physicsEngine) {
  30059. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30060. if (impostor) {
  30061. _this.physicsImpostor = impostor.clone(_this);
  30062. }
  30063. }
  30064. // Particles
  30065. for (index = 0; index < scene.particleSystems.length; index++) {
  30066. var system = scene.particleSystems[index];
  30067. if (system.emitter === source) {
  30068. system.clone(system.name, _this);
  30069. }
  30070. }
  30071. _this.computeWorldMatrix(true);
  30072. }
  30073. // Parent
  30074. if (parent !== null) {
  30075. _this.parent = parent;
  30076. }
  30077. return _this;
  30078. }
  30079. Object.defineProperty(Mesh, "FRONTSIDE", {
  30080. /**
  30081. * Mesh side orientation : usually the external or front surface
  30082. */
  30083. get: function () {
  30084. return Mesh._FRONTSIDE;
  30085. },
  30086. enumerable: true,
  30087. configurable: true
  30088. });
  30089. Object.defineProperty(Mesh, "BACKSIDE", {
  30090. /**
  30091. * Mesh side orientation : usually the internal or back surface
  30092. */
  30093. get: function () {
  30094. return Mesh._BACKSIDE;
  30095. },
  30096. enumerable: true,
  30097. configurable: true
  30098. });
  30099. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30100. /**
  30101. * Mesh side orientation : both internal and external or front and back surfaces
  30102. */
  30103. get: function () {
  30104. return Mesh._DOUBLESIDE;
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30110. /**
  30111. * Mesh side orientation : by default, `FRONTSIDE`
  30112. */
  30113. get: function () {
  30114. return Mesh._DEFAULTSIDE;
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. Object.defineProperty(Mesh, "NO_CAP", {
  30120. /**
  30121. * Mesh cap setting : no cap
  30122. */
  30123. get: function () {
  30124. return Mesh._NO_CAP;
  30125. },
  30126. enumerable: true,
  30127. configurable: true
  30128. });
  30129. Object.defineProperty(Mesh, "CAP_START", {
  30130. /**
  30131. * Mesh cap setting : one cap at the beginning of the mesh
  30132. */
  30133. get: function () {
  30134. return Mesh._CAP_START;
  30135. },
  30136. enumerable: true,
  30137. configurable: true
  30138. });
  30139. Object.defineProperty(Mesh, "CAP_END", {
  30140. /**
  30141. * Mesh cap setting : one cap at the end of the mesh
  30142. */
  30143. get: function () {
  30144. return Mesh._CAP_END;
  30145. },
  30146. enumerable: true,
  30147. configurable: true
  30148. });
  30149. Object.defineProperty(Mesh, "CAP_ALL", {
  30150. /**
  30151. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30152. */
  30153. get: function () {
  30154. return Mesh._CAP_ALL;
  30155. },
  30156. enumerable: true,
  30157. configurable: true
  30158. });
  30159. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30160. set: function (callback) {
  30161. if (this._onBeforeDrawObserver) {
  30162. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30163. }
  30164. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30165. },
  30166. enumerable: true,
  30167. configurable: true
  30168. });
  30169. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30170. get: function () {
  30171. return this._morphTargetManager;
  30172. },
  30173. set: function (value) {
  30174. if (this._morphTargetManager === value) {
  30175. return;
  30176. }
  30177. this._morphTargetManager = value;
  30178. this._syncGeometryWithMorphTargetManager();
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. Object.defineProperty(Mesh.prototype, "source", {
  30184. get: function () {
  30185. return this._source;
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30191. get: function () {
  30192. return this._unIndexed;
  30193. },
  30194. set: function (value) {
  30195. if (this._unIndexed !== value) {
  30196. this._unIndexed = value;
  30197. this._markSubMeshesAsAttributesDirty();
  30198. }
  30199. },
  30200. enumerable: true,
  30201. configurable: true
  30202. });
  30203. // Methods
  30204. /**
  30205. * Returns the string "Mesh".
  30206. */
  30207. Mesh.prototype.getClassName = function () {
  30208. return "Mesh";
  30209. };
  30210. /**
  30211. * Returns a string.
  30212. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30213. */
  30214. Mesh.prototype.toString = function (fullDetails) {
  30215. var ret = _super.prototype.toString.call(this, fullDetails);
  30216. ret += ", n vertices: " + this.getTotalVertices();
  30217. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30218. if (this.animations) {
  30219. for (var i = 0; i < this.animations.length; i++) {
  30220. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30221. }
  30222. }
  30223. if (fullDetails) {
  30224. if (this._geometry) {
  30225. var ib = this.getIndices();
  30226. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30227. if (vb && ib) {
  30228. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30229. }
  30230. }
  30231. else {
  30232. ret += ", flat shading: UNKNOWN";
  30233. }
  30234. }
  30235. return ret;
  30236. };
  30237. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30238. /**
  30239. * True if the mesh has some Levels Of Details (LOD).
  30240. * Returns a boolean.
  30241. */
  30242. get: function () {
  30243. return this._LODLevels.length > 0;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. /**
  30249. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30250. * @returns an array of {BABYLON.MeshLODLevel}
  30251. */
  30252. Mesh.prototype.getLODLevels = function () {
  30253. return this._LODLevels;
  30254. };
  30255. Mesh.prototype._sortLODLevels = function () {
  30256. this._LODLevels.sort(function (a, b) {
  30257. if (a.distance < b.distance) {
  30258. return 1;
  30259. }
  30260. if (a.distance > b.distance) {
  30261. return -1;
  30262. }
  30263. return 0;
  30264. });
  30265. };
  30266. /**
  30267. * Add a mesh as LOD level triggered at the given distance.
  30268. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30269. * @param {number} distance The distance from the center of the object to show this level
  30270. * @param {Mesh} mesh The mesh to be added as LOD level
  30271. * @return {Mesh} This mesh (for chaining)
  30272. */
  30273. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30274. if (mesh && mesh._masterMesh) {
  30275. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30276. return this;
  30277. }
  30278. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30279. this._LODLevels.push(level);
  30280. if (mesh) {
  30281. mesh._masterMesh = this;
  30282. }
  30283. this._sortLODLevels();
  30284. return this;
  30285. };
  30286. /**
  30287. * Returns the LOD level mesh at the passed distance or null if not found.
  30288. * It is related to the method `addLODLevel(distance, mesh)`.
  30289. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30290. * Returns an object Mesh or `null`.
  30291. */
  30292. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30293. for (var index = 0; index < this._LODLevels.length; index++) {
  30294. var level = this._LODLevels[index];
  30295. if (level.distance === distance) {
  30296. return level.mesh;
  30297. }
  30298. }
  30299. return null;
  30300. };
  30301. /**
  30302. * Remove a mesh from the LOD array
  30303. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30304. * @param {Mesh} mesh The mesh to be removed.
  30305. * @return {Mesh} This mesh (for chaining)
  30306. */
  30307. Mesh.prototype.removeLODLevel = function (mesh) {
  30308. for (var index = 0; index < this._LODLevels.length; index++) {
  30309. if (this._LODLevels[index].mesh === mesh) {
  30310. this._LODLevels.splice(index, 1);
  30311. if (mesh) {
  30312. mesh._masterMesh = null;
  30313. }
  30314. }
  30315. }
  30316. this._sortLODLevels();
  30317. return this;
  30318. };
  30319. /**
  30320. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30321. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30322. */
  30323. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30324. if (!this._LODLevels || this._LODLevels.length === 0) {
  30325. return this;
  30326. }
  30327. var bSphere;
  30328. if (boundingSphere) {
  30329. bSphere = boundingSphere;
  30330. }
  30331. else {
  30332. var boundingInfo = this.getBoundingInfo();
  30333. bSphere = boundingInfo.boundingSphere;
  30334. }
  30335. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30336. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30337. if (this.onLODLevelSelection) {
  30338. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30339. }
  30340. return this;
  30341. }
  30342. for (var index = 0; index < this._LODLevels.length; index++) {
  30343. var level = this._LODLevels[index];
  30344. if (level.distance < distanceToCamera) {
  30345. if (level.mesh) {
  30346. level.mesh._preActivate();
  30347. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30348. }
  30349. if (this.onLODLevelSelection) {
  30350. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30351. }
  30352. return level.mesh;
  30353. }
  30354. }
  30355. if (this.onLODLevelSelection) {
  30356. this.onLODLevelSelection(distanceToCamera, this, this);
  30357. }
  30358. return this;
  30359. };
  30360. Object.defineProperty(Mesh.prototype, "geometry", {
  30361. /**
  30362. * Returns the mesh internal Geometry object.
  30363. */
  30364. get: function () {
  30365. return this._geometry;
  30366. },
  30367. enumerable: true,
  30368. configurable: true
  30369. });
  30370. /**
  30371. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30372. */
  30373. Mesh.prototype.getTotalVertices = function () {
  30374. if (this._geometry === null || this._geometry === undefined) {
  30375. return 0;
  30376. }
  30377. return this._geometry.getTotalVertices();
  30378. };
  30379. /**
  30380. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30381. * 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.
  30382. * You can force the copy with forceCopy === true
  30383. * Returns null if the mesh has no geometry or no vertex buffer.
  30384. * Possible `kind` values :
  30385. * - BABYLON.VertexBuffer.PositionKind
  30386. * - BABYLON.VertexBuffer.UVKind
  30387. * - BABYLON.VertexBuffer.UV2Kind
  30388. * - BABYLON.VertexBuffer.UV3Kind
  30389. * - BABYLON.VertexBuffer.UV4Kind
  30390. * - BABYLON.VertexBuffer.UV5Kind
  30391. * - BABYLON.VertexBuffer.UV6Kind
  30392. * - BABYLON.VertexBuffer.ColorKind
  30393. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30394. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30395. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30396. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30397. */
  30398. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30399. if (!this._geometry) {
  30400. return null;
  30401. }
  30402. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30403. };
  30404. /**
  30405. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30406. * Returns `null` if the mesh has no geometry.
  30407. * Possible `kind` values :
  30408. * - BABYLON.VertexBuffer.PositionKind
  30409. * - BABYLON.VertexBuffer.UVKind
  30410. * - BABYLON.VertexBuffer.UV2Kind
  30411. * - BABYLON.VertexBuffer.UV3Kind
  30412. * - BABYLON.VertexBuffer.UV4Kind
  30413. * - BABYLON.VertexBuffer.UV5Kind
  30414. * - BABYLON.VertexBuffer.UV6Kind
  30415. * - BABYLON.VertexBuffer.ColorKind
  30416. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30417. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30418. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30419. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30420. */
  30421. Mesh.prototype.getVertexBuffer = function (kind) {
  30422. if (!this._geometry) {
  30423. return null;
  30424. }
  30425. return this._geometry.getVertexBuffer(kind);
  30426. };
  30427. /**
  30428. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30429. * Possible `kind` values :
  30430. * - BABYLON.VertexBuffer.PositionKind
  30431. * - BABYLON.VertexBuffer.UVKind
  30432. * - BABYLON.VertexBuffer.UV2Kind
  30433. * - BABYLON.VertexBuffer.UV3Kind
  30434. * - BABYLON.VertexBuffer.UV4Kind
  30435. * - BABYLON.VertexBuffer.UV5Kind
  30436. * - BABYLON.VertexBuffer.UV6Kind
  30437. * - BABYLON.VertexBuffer.ColorKind
  30438. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30439. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30440. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30441. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30442. */
  30443. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30444. if (!this._geometry) {
  30445. if (this._delayInfo) {
  30446. return this._delayInfo.indexOf(kind) !== -1;
  30447. }
  30448. return false;
  30449. }
  30450. return this._geometry.isVerticesDataPresent(kind);
  30451. };
  30452. /**
  30453. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30454. * Possible `kind` values :
  30455. * - BABYLON.VertexBuffer.PositionKind
  30456. * - BABYLON.VertexBuffer.UVKind
  30457. * - BABYLON.VertexBuffer.UV2Kind
  30458. * - BABYLON.VertexBuffer.UV3Kind
  30459. * - BABYLON.VertexBuffer.UV4Kind
  30460. * - BABYLON.VertexBuffer.UV5Kind
  30461. * - BABYLON.VertexBuffer.UV6Kind
  30462. * - BABYLON.VertexBuffer.ColorKind
  30463. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30464. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30465. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30466. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30467. */
  30468. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30469. if (!this._geometry) {
  30470. if (this._delayInfo) {
  30471. return this._delayInfo.indexOf(kind) !== -1;
  30472. }
  30473. return false;
  30474. }
  30475. return this._geometry.isVertexBufferUpdatable(kind);
  30476. };
  30477. /**
  30478. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30479. * Possible `kind` values :
  30480. * - BABYLON.VertexBuffer.PositionKind
  30481. * - BABYLON.VertexBuffer.UVKind
  30482. * - BABYLON.VertexBuffer.UV2Kind
  30483. * - BABYLON.VertexBuffer.UV3Kind
  30484. * - BABYLON.VertexBuffer.UV4Kind
  30485. * - BABYLON.VertexBuffer.UV5Kind
  30486. * - BABYLON.VertexBuffer.UV6Kind
  30487. * - BABYLON.VertexBuffer.ColorKind
  30488. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30489. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30490. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30491. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30492. */
  30493. Mesh.prototype.getVerticesDataKinds = function () {
  30494. if (!this._geometry) {
  30495. var result = new Array();
  30496. if (this._delayInfo) {
  30497. this._delayInfo.forEach(function (kind, index, array) {
  30498. result.push(kind);
  30499. });
  30500. }
  30501. return result;
  30502. }
  30503. return this._geometry.getVerticesDataKinds();
  30504. };
  30505. /**
  30506. * Returns a positive integer : the total number of indices in this mesh geometry.
  30507. * Returns zero if the mesh has no geometry.
  30508. */
  30509. Mesh.prototype.getTotalIndices = function () {
  30510. if (!this._geometry) {
  30511. return 0;
  30512. }
  30513. return this._geometry.getTotalIndices();
  30514. };
  30515. /**
  30516. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30517. * 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.
  30518. * Returns an empty array if the mesh has no geometry.
  30519. */
  30520. Mesh.prototype.getIndices = function (copyWhenShared) {
  30521. if (!this._geometry) {
  30522. return [];
  30523. }
  30524. return this._geometry.getIndices(copyWhenShared);
  30525. };
  30526. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30527. get: function () {
  30528. return this._masterMesh !== null && this._masterMesh !== undefined;
  30529. },
  30530. enumerable: true,
  30531. configurable: true
  30532. });
  30533. /**
  30534. * Determine if the current mesh is ready to be rendered
  30535. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30536. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30537. * @returns true if all associated assets are ready (material, textures, shaders)
  30538. */
  30539. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30540. if (completeCheck === void 0) { completeCheck = false; }
  30541. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30542. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30543. return false;
  30544. }
  30545. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30546. return false;
  30547. }
  30548. if (!this.subMeshes || this.subMeshes.length === 0) {
  30549. return true;
  30550. }
  30551. if (!completeCheck) {
  30552. return true;
  30553. }
  30554. var engine = this.getEngine();
  30555. var scene = this.getScene();
  30556. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30557. this.computeWorldMatrix();
  30558. var mat = this.material || scene.defaultMaterial;
  30559. if (mat) {
  30560. if (mat.storeEffectOnSubMeshes) {
  30561. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30562. var subMesh = _a[_i];
  30563. var effectiveMaterial = subMesh.getMaterial();
  30564. if (effectiveMaterial) {
  30565. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30566. return false;
  30567. }
  30568. }
  30569. }
  30570. }
  30571. else {
  30572. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30573. return false;
  30574. }
  30575. }
  30576. }
  30577. // Shadows
  30578. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30579. var light = _c[_b];
  30580. var generator = light.getShadowGenerator();
  30581. if (generator) {
  30582. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30583. var subMesh = _e[_d];
  30584. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30585. return false;
  30586. }
  30587. }
  30588. }
  30589. }
  30590. // LOD
  30591. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30592. var lod = _g[_f];
  30593. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30594. return false;
  30595. }
  30596. }
  30597. return true;
  30598. };
  30599. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30600. /**
  30601. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30602. * This property is pertinent only for updatable parametric shapes.
  30603. */
  30604. get: function () {
  30605. return this._areNormalsFrozen;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. /**
  30611. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30612. * It has no effect at all on other shapes.
  30613. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30614. * Returns the Mesh.
  30615. */
  30616. Mesh.prototype.freezeNormals = function () {
  30617. this._areNormalsFrozen = true;
  30618. return this;
  30619. };
  30620. /**
  30621. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30622. * It has no effect at all on other shapes.
  30623. * It reactivates the mesh normals computation if it was previously frozen.
  30624. * Returns the Mesh.
  30625. */
  30626. Mesh.prototype.unfreezeNormals = function () {
  30627. this._areNormalsFrozen = false;
  30628. return this;
  30629. };
  30630. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30631. /**
  30632. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30633. */
  30634. set: function (count) {
  30635. this._overridenInstanceCount = count;
  30636. },
  30637. enumerable: true,
  30638. configurable: true
  30639. });
  30640. // Methods
  30641. Mesh.prototype._preActivate = function () {
  30642. var sceneRenderId = this.getScene().getRenderId();
  30643. if (this._preActivateId === sceneRenderId) {
  30644. return this;
  30645. }
  30646. this._preActivateId = sceneRenderId;
  30647. this._visibleInstances = null;
  30648. return this;
  30649. };
  30650. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30651. if (this._visibleInstances) {
  30652. this._visibleInstances.intermediateDefaultRenderId = renderId;
  30653. }
  30654. return this;
  30655. };
  30656. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  30657. if (!this._visibleInstances) {
  30658. this._visibleInstances = {};
  30659. this._visibleInstances.defaultRenderId = renderId;
  30660. this._visibleInstances.selfDefaultRenderId = this._renderId;
  30661. }
  30662. if (!this._visibleInstances[renderId]) {
  30663. this._visibleInstances[renderId] = new Array();
  30664. }
  30665. this._visibleInstances[renderId].push(instance);
  30666. return this;
  30667. };
  30668. /**
  30669. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  30670. * This means the mesh underlying bounding box and sphere are recomputed.
  30671. * Returns the Mesh.
  30672. */
  30673. Mesh.prototype.refreshBoundingInfo = function () {
  30674. return this._refreshBoundingInfo(false);
  30675. };
  30676. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  30677. if (this._boundingInfo && this._boundingInfo.isLocked) {
  30678. return this;
  30679. }
  30680. var data = this._getPositionData(applySkeleton);
  30681. if (data) {
  30682. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  30683. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30684. }
  30685. if (this.subMeshes) {
  30686. for (var index = 0; index < this.subMeshes.length; index++) {
  30687. this.subMeshes[index].refreshBoundingInfo();
  30688. }
  30689. }
  30690. this._updateBoundingInfo();
  30691. return this;
  30692. };
  30693. Mesh.prototype._getPositionData = function (applySkeleton) {
  30694. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30695. if (data && applySkeleton && this.skeleton) {
  30696. data = BABYLON.Tools.Slice(data);
  30697. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30698. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30699. if (matricesWeightsData && matricesIndicesData) {
  30700. var needExtras = this.numBoneInfluencers > 4;
  30701. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30702. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30703. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  30704. var tempVector = BABYLON.Tmp.Vector3[0];
  30705. var finalMatrix = BABYLON.Tmp.Matrix[0];
  30706. var tempMatrix = BABYLON.Tmp.Matrix[1];
  30707. var matWeightIdx = 0;
  30708. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  30709. finalMatrix.reset();
  30710. var inf;
  30711. var weight;
  30712. for (inf = 0; inf < 4; inf++) {
  30713. weight = matricesWeightsData[matWeightIdx + inf];
  30714. if (weight <= 0)
  30715. break;
  30716. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30717. finalMatrix.addToSelf(tempMatrix);
  30718. }
  30719. if (needExtras) {
  30720. for (inf = 0; inf < 4; inf++) {
  30721. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30722. if (weight <= 0)
  30723. break;
  30724. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30725. finalMatrix.addToSelf(tempMatrix);
  30726. }
  30727. }
  30728. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  30729. tempVector.toArray(data, index);
  30730. }
  30731. }
  30732. }
  30733. return data;
  30734. };
  30735. Mesh.prototype._createGlobalSubMesh = function (force) {
  30736. var totalVertices = this.getTotalVertices();
  30737. if (!totalVertices || !this.getIndices()) {
  30738. return null;
  30739. }
  30740. // Check if we need to recreate the submeshes
  30741. if (this.subMeshes && this.subMeshes.length > 0) {
  30742. var ib = this.getIndices();
  30743. if (!ib) {
  30744. return null;
  30745. }
  30746. var totalIndices = ib.length;
  30747. var needToRecreate = false;
  30748. if (force) {
  30749. needToRecreate = true;
  30750. }
  30751. else {
  30752. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30753. var submesh = _a[_i];
  30754. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  30755. needToRecreate = true;
  30756. break;
  30757. }
  30758. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  30759. needToRecreate = true;
  30760. break;
  30761. }
  30762. }
  30763. }
  30764. if (!needToRecreate) {
  30765. return this.subMeshes[0];
  30766. }
  30767. }
  30768. this.releaseSubMeshes();
  30769. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  30770. };
  30771. Mesh.prototype.subdivide = function (count) {
  30772. if (count < 1) {
  30773. return;
  30774. }
  30775. var totalIndices = this.getTotalIndices();
  30776. var subdivisionSize = (totalIndices / count) | 0;
  30777. var offset = 0;
  30778. // Ensure that subdivisionSize is a multiple of 3
  30779. while (subdivisionSize % 3 !== 0) {
  30780. subdivisionSize++;
  30781. }
  30782. this.releaseSubMeshes();
  30783. for (var index = 0; index < count; index++) {
  30784. if (offset >= totalIndices) {
  30785. break;
  30786. }
  30787. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  30788. offset += subdivisionSize;
  30789. }
  30790. this.synchronizeInstances();
  30791. };
  30792. /**
  30793. * Sets the vertex data of the mesh geometry for the requested `kind`.
  30794. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  30795. * The `data` are either a numeric array either a Float32Array.
  30796. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  30797. * 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).
  30798. * Note that a new underlying VertexBuffer object is created each call.
  30799. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  30800. *
  30801. * Possible `kind` values :
  30802. * - BABYLON.VertexBuffer.PositionKind
  30803. * - BABYLON.VertexBuffer.UVKind
  30804. * - BABYLON.VertexBuffer.UV2Kind
  30805. * - BABYLON.VertexBuffer.UV3Kind
  30806. * - BABYLON.VertexBuffer.UV4Kind
  30807. * - BABYLON.VertexBuffer.UV5Kind
  30808. * - BABYLON.VertexBuffer.UV6Kind
  30809. * - BABYLON.VertexBuffer.ColorKind
  30810. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30811. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30812. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30813. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30814. *
  30815. * Returns the Mesh.
  30816. */
  30817. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30818. if (updatable === void 0) { updatable = false; }
  30819. if (!this._geometry) {
  30820. var vertexData = new BABYLON.VertexData();
  30821. vertexData.set(data, kind);
  30822. var scene = this.getScene();
  30823. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  30824. }
  30825. else {
  30826. this._geometry.setVerticesData(kind, data, updatable, stride);
  30827. }
  30828. return this;
  30829. };
  30830. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  30831. if (updatable === void 0) { updatable = true; }
  30832. var vb = this.getVertexBuffer(kind);
  30833. if (!vb || vb.isUpdatable() === updatable) {
  30834. return;
  30835. }
  30836. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  30837. };
  30838. /**
  30839. * Sets the mesh VertexBuffer.
  30840. * Returns the Mesh.
  30841. */
  30842. Mesh.prototype.setVerticesBuffer = function (buffer) {
  30843. if (!this._geometry) {
  30844. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  30845. }
  30846. this._geometry.setVerticesBuffer(buffer);
  30847. return this;
  30848. };
  30849. /**
  30850. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  30851. * If the mesh has no geometry, it is simply returned as it is.
  30852. * The `data` are either a numeric array either a Float32Array.
  30853. * No new underlying VertexBuffer object is created.
  30854. * 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.
  30855. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  30856. *
  30857. * Possible `kind` values :
  30858. * - BABYLON.VertexBuffer.PositionKind
  30859. * - BABYLON.VertexBuffer.UVKind
  30860. * - BABYLON.VertexBuffer.UV2Kind
  30861. * - BABYLON.VertexBuffer.UV3Kind
  30862. * - BABYLON.VertexBuffer.UV4Kind
  30863. * - BABYLON.VertexBuffer.UV5Kind
  30864. * - BABYLON.VertexBuffer.UV6Kind
  30865. * - BABYLON.VertexBuffer.ColorKind
  30866. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30867. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30868. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30869. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30870. *
  30871. * Returns the Mesh.
  30872. */
  30873. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  30874. if (!this._geometry) {
  30875. return this;
  30876. }
  30877. if (!makeItUnique) {
  30878. this._geometry.updateVerticesData(kind, data, updateExtends);
  30879. }
  30880. else {
  30881. this.makeGeometryUnique();
  30882. this.updateVerticesData(kind, data, updateExtends, false);
  30883. }
  30884. return this;
  30885. };
  30886. /**
  30887. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  30888. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  30889. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  30890. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  30891. * Returns the Mesh.
  30892. */
  30893. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  30894. if (computeNormals === void 0) { computeNormals = true; }
  30895. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30896. if (!positions) {
  30897. return this;
  30898. }
  30899. positionFunction(positions);
  30900. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  30901. if (computeNormals) {
  30902. var indices = this.getIndices();
  30903. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30904. if (!normals) {
  30905. return this;
  30906. }
  30907. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  30908. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  30909. }
  30910. return this;
  30911. };
  30912. /**
  30913. * Creates a un-shared specific occurence of the geometry for the mesh.
  30914. * Returns the Mesh.
  30915. */
  30916. Mesh.prototype.makeGeometryUnique = function () {
  30917. if (!this._geometry) {
  30918. return this;
  30919. }
  30920. var oldGeometry = this._geometry;
  30921. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  30922. oldGeometry.releaseForMesh(this, true);
  30923. geometry.applyToMesh(this);
  30924. return this;
  30925. };
  30926. /**
  30927. * Sets the mesh indices.
  30928. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  30929. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  30930. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  30931. * This method creates a new index buffer each call.
  30932. * Returns the Mesh.
  30933. */
  30934. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  30935. if (totalVertices === void 0) { totalVertices = null; }
  30936. if (updatable === void 0) { updatable = false; }
  30937. if (!this._geometry) {
  30938. var vertexData = new BABYLON.VertexData();
  30939. vertexData.indices = indices;
  30940. var scene = this.getScene();
  30941. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  30942. }
  30943. else {
  30944. this._geometry.setIndices(indices, totalVertices, updatable);
  30945. }
  30946. return this;
  30947. };
  30948. /**
  30949. * Update the current index buffer
  30950. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  30951. * Returns the Mesh.
  30952. */
  30953. Mesh.prototype.updateIndices = function (indices, offset) {
  30954. if (!this._geometry) {
  30955. return this;
  30956. }
  30957. this._geometry.updateIndices(indices, offset);
  30958. return this;
  30959. };
  30960. /**
  30961. * Invert the geometry to move from a right handed system to a left handed one.
  30962. * Returns the Mesh.
  30963. */
  30964. Mesh.prototype.toLeftHanded = function () {
  30965. if (!this._geometry) {
  30966. return this;
  30967. }
  30968. this._geometry.toLeftHanded();
  30969. return this;
  30970. };
  30971. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  30972. if (!this._geometry) {
  30973. return this;
  30974. }
  30975. var engine = this.getScene().getEngine();
  30976. // Wireframe
  30977. var indexToBind;
  30978. if (this._unIndexed) {
  30979. indexToBind = null;
  30980. }
  30981. else {
  30982. switch (fillMode) {
  30983. case BABYLON.Material.PointFillMode:
  30984. indexToBind = null;
  30985. break;
  30986. case BABYLON.Material.WireFrameFillMode:
  30987. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  30988. break;
  30989. default:
  30990. case BABYLON.Material.TriangleFillMode:
  30991. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  30992. break;
  30993. }
  30994. }
  30995. // VBOs
  30996. this._geometry._bind(effect, indexToBind);
  30997. return this;
  30998. };
  30999. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31000. if (alternate === void 0) { alternate = false; }
  31001. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31002. return this;
  31003. }
  31004. this.onBeforeDrawObservable.notifyObservers(this);
  31005. var scene = this.getScene();
  31006. var engine = scene.getEngine();
  31007. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31008. // or triangles as points
  31009. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31010. }
  31011. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31012. // Triangles as wireframe
  31013. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31014. }
  31015. else {
  31016. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31017. }
  31018. if (scene._isAlternateRenderingEnabled && !alternate) {
  31019. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31020. if (!effect || !scene.activeCamera) {
  31021. return this;
  31022. }
  31023. scene._switchToAlternateCameraConfiguration(true);
  31024. this._effectiveMaterial.bindView(effect);
  31025. this._effectiveMaterial.bindViewProjection(effect);
  31026. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31027. this._draw(subMesh, fillMode, instancesCount, true);
  31028. engine.setViewport(scene.activeCamera.viewport);
  31029. scene._switchToAlternateCameraConfiguration(false);
  31030. this._effectiveMaterial.bindView(effect);
  31031. this._effectiveMaterial.bindViewProjection(effect);
  31032. }
  31033. return this;
  31034. };
  31035. /**
  31036. * Registers for this mesh a javascript function called just before the rendering process.
  31037. * This function is passed the current mesh.
  31038. * Return the Mesh.
  31039. */
  31040. Mesh.prototype.registerBeforeRender = function (func) {
  31041. this.onBeforeRenderObservable.add(func);
  31042. return this;
  31043. };
  31044. /**
  31045. * Disposes a previously registered javascript function called before the rendering.
  31046. * This function is passed the current mesh.
  31047. * Returns the Mesh.
  31048. */
  31049. Mesh.prototype.unregisterBeforeRender = function (func) {
  31050. this.onBeforeRenderObservable.removeCallback(func);
  31051. return this;
  31052. };
  31053. /**
  31054. * Registers for this mesh a javascript function called just after the rendering is complete.
  31055. * This function is passed the current mesh.
  31056. * Returns the Mesh.
  31057. */
  31058. Mesh.prototype.registerAfterRender = function (func) {
  31059. this.onAfterRenderObservable.add(func);
  31060. return this;
  31061. };
  31062. /**
  31063. * Disposes a previously registered javascript function called after the rendering.
  31064. * This function is passed the current mesh.
  31065. * Return the Mesh.
  31066. */
  31067. Mesh.prototype.unregisterAfterRender = function (func) {
  31068. this.onAfterRenderObservable.removeCallback(func);
  31069. return this;
  31070. };
  31071. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31072. var scene = this.getScene();
  31073. this._batchCache.mustReturn = false;
  31074. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31075. this._batchCache.visibleInstances[subMeshId] = null;
  31076. if (this._visibleInstances) {
  31077. var currentRenderId = scene.getRenderId();
  31078. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31079. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31080. var selfRenderId = this._renderId;
  31081. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31082. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31083. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31084. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31085. }
  31086. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31087. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31088. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31089. this._batchCache.mustReturn = true;
  31090. return this._batchCache;
  31091. }
  31092. if (currentRenderId !== selfRenderId) {
  31093. this._batchCache.renderSelf[subMeshId] = false;
  31094. }
  31095. }
  31096. this._renderIdForInstances[subMeshId] = currentRenderId;
  31097. }
  31098. return this._batchCache;
  31099. };
  31100. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31101. var visibleInstances = batch.visibleInstances[subMesh._id];
  31102. if (!visibleInstances) {
  31103. return this;
  31104. }
  31105. var matricesCount = visibleInstances.length + 1;
  31106. var bufferSize = matricesCount * 16 * 4;
  31107. var currentInstancesBufferSize = this._instancesBufferSize;
  31108. var instancesBuffer = this._instancesBuffer;
  31109. while (this._instancesBufferSize < bufferSize) {
  31110. this._instancesBufferSize *= 2;
  31111. }
  31112. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31113. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31114. }
  31115. var offset = 0;
  31116. var instancesCount = 0;
  31117. var world = this.getWorldMatrix();
  31118. if (batch.renderSelf[subMesh._id]) {
  31119. world.copyToArray(this._instancesData, offset);
  31120. offset += 16;
  31121. instancesCount++;
  31122. }
  31123. if (visibleInstances) {
  31124. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31125. var instance = visibleInstances[instanceIndex];
  31126. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31127. offset += 16;
  31128. instancesCount++;
  31129. }
  31130. }
  31131. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31132. if (instancesBuffer) {
  31133. instancesBuffer.dispose();
  31134. }
  31135. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31136. this._instancesBuffer = instancesBuffer;
  31137. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31138. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31139. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31140. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31141. }
  31142. else {
  31143. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31144. }
  31145. this._bind(subMesh, effect, fillMode);
  31146. this._draw(subMesh, fillMode, instancesCount);
  31147. engine.unbindInstanceAttributes();
  31148. return this;
  31149. };
  31150. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31151. var scene = this.getScene();
  31152. var engine = scene.getEngine();
  31153. if (hardwareInstancedRendering) {
  31154. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31155. }
  31156. else {
  31157. if (batch.renderSelf[subMesh._id]) {
  31158. // Draw
  31159. if (onBeforeDraw) {
  31160. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31161. }
  31162. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31163. }
  31164. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31165. if (visibleInstancesForSubMesh) {
  31166. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31167. var instance = visibleInstancesForSubMesh[instanceIndex];
  31168. // World
  31169. var world = instance.getWorldMatrix();
  31170. if (onBeforeDraw) {
  31171. onBeforeDraw(true, world, effectiveMaterial);
  31172. }
  31173. // Draw
  31174. this._draw(subMesh, fillMode);
  31175. }
  31176. }
  31177. }
  31178. return this;
  31179. };
  31180. /**
  31181. * Triggers the draw call for the mesh.
  31182. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31183. * Returns the Mesh.
  31184. */
  31185. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31186. this.checkOcclusionQuery();
  31187. if (this._isOccluded) {
  31188. return this;
  31189. }
  31190. var scene = this.getScene();
  31191. // Managing instances
  31192. var batch = this._getInstancesRenderList(subMesh._id);
  31193. if (batch.mustReturn) {
  31194. return this;
  31195. }
  31196. // Checking geometry state
  31197. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31198. return this;
  31199. }
  31200. this.onBeforeRenderObservable.notifyObservers(this);
  31201. var engine = scene.getEngine();
  31202. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31203. // Material
  31204. var material = subMesh.getMaterial();
  31205. if (!material) {
  31206. return this;
  31207. }
  31208. this._effectiveMaterial = material;
  31209. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31210. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31211. return this;
  31212. }
  31213. }
  31214. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31215. return this;
  31216. }
  31217. // Alpha mode
  31218. if (enableAlphaMode) {
  31219. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31220. }
  31221. // Outline - step 1
  31222. var savedDepthWrite = engine.getDepthWrite();
  31223. if (this.renderOutline) {
  31224. engine.setDepthWrite(false);
  31225. scene.getOutlineRenderer().render(subMesh, batch);
  31226. engine.setDepthWrite(savedDepthWrite);
  31227. }
  31228. var effect;
  31229. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31230. effect = subMesh.effect;
  31231. }
  31232. else {
  31233. effect = this._effectiveMaterial.getEffect();
  31234. }
  31235. if (!effect) {
  31236. return this;
  31237. }
  31238. var sideOrientation = this.overrideMaterialSideOrientation;
  31239. if (sideOrientation == null) {
  31240. sideOrientation = this._effectiveMaterial.sideOrientation;
  31241. if (this._getWorldMatrixDeterminant() < 0) {
  31242. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31243. }
  31244. }
  31245. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31246. if (this._effectiveMaterial.forceDepthWrite) {
  31247. engine.setDepthWrite(true);
  31248. }
  31249. // Bind
  31250. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31251. if (!hardwareInstancedRendering) {
  31252. this._bind(subMesh, effect, fillMode);
  31253. }
  31254. var world = this.getWorldMatrix();
  31255. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31256. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31257. }
  31258. else {
  31259. this._effectiveMaterial.bind(world, this);
  31260. }
  31261. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31262. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31263. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31264. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31265. }
  31266. // Draw
  31267. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31268. // Unbind
  31269. this._effectiveMaterial.unbind();
  31270. // Outline - step 2
  31271. if (this.renderOutline && savedDepthWrite) {
  31272. engine.setDepthWrite(true);
  31273. engine.setColorWrite(false);
  31274. scene.getOutlineRenderer().render(subMesh, batch);
  31275. engine.setColorWrite(true);
  31276. }
  31277. // Overlay
  31278. if (this.renderOverlay) {
  31279. var currentMode = engine.getAlphaMode();
  31280. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31281. scene.getOutlineRenderer().render(subMesh, batch, true);
  31282. engine.setAlphaMode(currentMode);
  31283. }
  31284. this.onAfterRenderObservable.notifyObservers(this);
  31285. return this;
  31286. };
  31287. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31288. if (isInstance && effectiveMaterial) {
  31289. effectiveMaterial.bindOnlyWorldMatrix(world);
  31290. }
  31291. };
  31292. /**
  31293. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31294. */
  31295. Mesh.prototype.getEmittedParticleSystems = function () {
  31296. var results = new Array();
  31297. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31298. var particleSystem = this.getScene().particleSystems[index];
  31299. if (particleSystem.emitter === this) {
  31300. results.push(particleSystem);
  31301. }
  31302. }
  31303. return results;
  31304. };
  31305. /**
  31306. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31307. */
  31308. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31309. var results = new Array();
  31310. var descendants = this.getDescendants();
  31311. descendants.push(this);
  31312. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31313. var particleSystem = this.getScene().particleSystems[index];
  31314. var emitter = particleSystem.emitter;
  31315. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31316. results.push(particleSystem);
  31317. }
  31318. }
  31319. return results;
  31320. };
  31321. Mesh.prototype._checkDelayState = function () {
  31322. var scene = this.getScene();
  31323. if (this._geometry) {
  31324. this._geometry.load(scene);
  31325. }
  31326. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31328. this._queueLoad(scene);
  31329. }
  31330. return this;
  31331. };
  31332. Mesh.prototype._queueLoad = function (scene) {
  31333. var _this = this;
  31334. scene._addPendingData(this);
  31335. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31336. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31337. if (data instanceof ArrayBuffer) {
  31338. _this._delayLoadingFunction(data, _this);
  31339. }
  31340. else {
  31341. _this._delayLoadingFunction(JSON.parse(data), _this);
  31342. }
  31343. _this.instances.forEach(function (instance) {
  31344. instance._syncSubMeshes();
  31345. });
  31346. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31347. scene._removePendingData(_this);
  31348. }, function () { }, scene.database, getBinaryData);
  31349. return this;
  31350. };
  31351. /**
  31352. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31353. */
  31354. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31355. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31356. return false;
  31357. }
  31358. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31359. return false;
  31360. }
  31361. this._checkDelayState();
  31362. return true;
  31363. };
  31364. /**
  31365. * Sets the mesh material by the material or multiMaterial `id` property.
  31366. * The material `id` is a string identifying the material or the multiMaterial.
  31367. * This method returns the Mesh.
  31368. */
  31369. Mesh.prototype.setMaterialByID = function (id) {
  31370. var materials = this.getScene().materials;
  31371. var index;
  31372. for (index = materials.length - 1; index > -1; index--) {
  31373. if (materials[index].id === id) {
  31374. this.material = materials[index];
  31375. return this;
  31376. }
  31377. }
  31378. // Multi
  31379. var multiMaterials = this.getScene().multiMaterials;
  31380. for (index = multiMaterials.length - 1; index > -1; index--) {
  31381. if (multiMaterials[index].id === id) {
  31382. this.material = multiMaterials[index];
  31383. return this;
  31384. }
  31385. }
  31386. return this;
  31387. };
  31388. /**
  31389. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31390. */
  31391. Mesh.prototype.getAnimatables = function () {
  31392. var results = new Array();
  31393. if (this.material) {
  31394. results.push(this.material);
  31395. }
  31396. if (this.skeleton) {
  31397. results.push(this.skeleton);
  31398. }
  31399. return results;
  31400. };
  31401. /**
  31402. * Modifies the mesh geometry according to the passed transformation matrix.
  31403. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31404. * The mesh normals are modified accordingly the same transformation.
  31405. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31406. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31407. * Returns the Mesh.
  31408. */
  31409. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31410. // Position
  31411. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31412. return this;
  31413. }
  31414. var submeshes = this.subMeshes.splice(0);
  31415. this._resetPointsArrayCache();
  31416. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31417. var temp = new Array();
  31418. var index;
  31419. for (index = 0; index < data.length; index += 3) {
  31420. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31421. }
  31422. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31423. // Normals
  31424. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31425. return this;
  31426. }
  31427. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31428. temp = [];
  31429. for (index = 0; index < data.length; index += 3) {
  31430. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31431. }
  31432. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31433. // flip faces?
  31434. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31435. this.flipFaces();
  31436. }
  31437. // Restore submeshes
  31438. this.releaseSubMeshes();
  31439. this.subMeshes = submeshes;
  31440. return this;
  31441. };
  31442. /**
  31443. * Modifies the mesh geometry according to its own current World Matrix.
  31444. * The mesh World Matrix is then reset.
  31445. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31446. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31447. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31448. * Returns the Mesh.
  31449. */
  31450. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31451. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31452. this.scaling.copyFromFloats(1, 1, 1);
  31453. this.position.copyFromFloats(0, 0, 0);
  31454. this.rotation.copyFromFloats(0, 0, 0);
  31455. //only if quaternion is already set
  31456. if (this.rotationQuaternion) {
  31457. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31458. }
  31459. this._worldMatrix = BABYLON.Matrix.Identity();
  31460. return this;
  31461. };
  31462. Object.defineProperty(Mesh.prototype, "_positions", {
  31463. // Cache
  31464. get: function () {
  31465. if (this._geometry) {
  31466. return this._geometry._positions;
  31467. }
  31468. return null;
  31469. },
  31470. enumerable: true,
  31471. configurable: true
  31472. });
  31473. Mesh.prototype._resetPointsArrayCache = function () {
  31474. if (this._geometry) {
  31475. this._geometry._resetPointsArrayCache();
  31476. }
  31477. return this;
  31478. };
  31479. Mesh.prototype._generatePointsArray = function () {
  31480. if (this._geometry) {
  31481. return this._geometry._generatePointsArray();
  31482. }
  31483. return false;
  31484. };
  31485. /**
  31486. * Returns a new Mesh object generated from the current mesh properties.
  31487. * This method must not get confused with createInstance().
  31488. * The parameter `name` is a string, the name given to the new mesh.
  31489. * The optional parameter `newParent` can be any Node object (default `null`).
  31490. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31491. * 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.
  31492. */
  31493. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31494. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31495. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31496. };
  31497. /**
  31498. * Releases resources associated with this mesh.
  31499. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31500. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31501. */
  31502. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31503. var _this = this;
  31504. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31505. this.morphTargetManager = null;
  31506. if (this._geometry) {
  31507. this._geometry.releaseForMesh(this, true);
  31508. }
  31509. // Sources
  31510. var meshes = this.getScene().meshes;
  31511. meshes.forEach(function (abstractMesh) {
  31512. var mesh = abstractMesh;
  31513. if (mesh._source && mesh._source === _this) {
  31514. mesh._source = null;
  31515. }
  31516. });
  31517. this._source = null;
  31518. // Instances
  31519. if (this._instancesBuffer) {
  31520. this._instancesBuffer.dispose();
  31521. this._instancesBuffer = null;
  31522. }
  31523. while (this.instances.length) {
  31524. this.instances[0].dispose();
  31525. }
  31526. // Effect layers.
  31527. var effectLayers = this.getScene().effectLayers;
  31528. for (var i = 0; i < effectLayers.length; i++) {
  31529. var effectLayer = effectLayers[i];
  31530. if (effectLayer) {
  31531. effectLayer._disposeMesh(this);
  31532. }
  31533. }
  31534. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31535. };
  31536. /**
  31537. * Modifies the mesh geometry according to a displacement map.
  31538. * 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.
  31539. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31540. * This method returns nothing.
  31541. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31542. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31543. * 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.
  31544. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31545. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31546. *
  31547. * Returns the Mesh.
  31548. */
  31549. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31550. var _this = this;
  31551. var scene = this.getScene();
  31552. var onload = function (img) {
  31553. // Getting height map data
  31554. var canvas = document.createElement("canvas");
  31555. var context = canvas.getContext("2d");
  31556. var heightMapWidth = img.width;
  31557. var heightMapHeight = img.height;
  31558. canvas.width = heightMapWidth;
  31559. canvas.height = heightMapHeight;
  31560. context.drawImage(img, 0, 0);
  31561. // Create VertexData from map data
  31562. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31563. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31564. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31565. //execute success callback, if set
  31566. if (onSuccess) {
  31567. onSuccess(_this);
  31568. }
  31569. };
  31570. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31571. return this;
  31572. };
  31573. /**
  31574. * Modifies the mesh geometry according to a displacementMap buffer.
  31575. * 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.
  31576. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31577. * This method returns nothing.
  31578. * 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.
  31579. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31580. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31581. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31582. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31583. *
  31584. * Returns the Mesh.
  31585. */
  31586. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31587. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31588. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31589. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31590. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31591. return this;
  31592. }
  31593. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31594. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31595. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31596. var position = BABYLON.Vector3.Zero();
  31597. var normal = BABYLON.Vector3.Zero();
  31598. var uv = BABYLON.Vector2.Zero();
  31599. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31600. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31601. for (var index = 0; index < positions.length; index += 3) {
  31602. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31603. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31604. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31605. // Compute height
  31606. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31607. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31608. var pos = (u + v * heightMapWidth) * 4;
  31609. var r = buffer[pos] / 255.0;
  31610. var g = buffer[pos + 1] / 255.0;
  31611. var b = buffer[pos + 2] / 255.0;
  31612. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31613. normal.normalize();
  31614. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31615. position = position.add(normal);
  31616. position.toArray(positions, index);
  31617. }
  31618. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31619. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31620. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31621. return this;
  31622. };
  31623. /**
  31624. * Modify the mesh to get a flat shading rendering.
  31625. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31626. * This method returns the Mesh.
  31627. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31628. */
  31629. Mesh.prototype.convertToFlatShadedMesh = function () {
  31630. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31631. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31632. var kinds = this.getVerticesDataKinds();
  31633. var vbs = {};
  31634. var data = {};
  31635. var newdata = {};
  31636. var updatableNormals = false;
  31637. var kindIndex;
  31638. var kind;
  31639. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31640. kind = kinds[kindIndex];
  31641. var vertexBuffer = this.getVertexBuffer(kind);
  31642. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31643. updatableNormals = vertexBuffer.isUpdatable();
  31644. kinds.splice(kindIndex, 1);
  31645. kindIndex--;
  31646. continue;
  31647. }
  31648. vbs[kind] = vertexBuffer;
  31649. data[kind] = vbs[kind].getData();
  31650. newdata[kind] = [];
  31651. }
  31652. // Save previous submeshes
  31653. var previousSubmeshes = this.subMeshes.slice(0);
  31654. var indices = this.getIndices();
  31655. var totalIndices = this.getTotalIndices();
  31656. // Generating unique vertices per face
  31657. var index;
  31658. for (index = 0; index < totalIndices; index++) {
  31659. var vertexIndex = indices[index];
  31660. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31661. kind = kinds[kindIndex];
  31662. var stride = vbs[kind].getStrideSize();
  31663. for (var offset = 0; offset < stride; offset++) {
  31664. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31665. }
  31666. }
  31667. }
  31668. // Updating faces & normal
  31669. var normals = [];
  31670. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  31671. for (index = 0; index < totalIndices; index += 3) {
  31672. indices[index] = index;
  31673. indices[index + 1] = index + 1;
  31674. indices[index + 2] = index + 2;
  31675. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  31676. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  31677. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  31678. var p1p2 = p1.subtract(p2);
  31679. var p3p2 = p3.subtract(p2);
  31680. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  31681. // Store same normals for every vertex
  31682. for (var localIndex = 0; localIndex < 3; localIndex++) {
  31683. normals.push(normal.x);
  31684. normals.push(normal.y);
  31685. normals.push(normal.z);
  31686. }
  31687. }
  31688. this.setIndices(indices);
  31689. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  31690. // Updating vertex buffers
  31691. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31692. kind = kinds[kindIndex];
  31693. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31694. }
  31695. // Updating submeshes
  31696. this.releaseSubMeshes();
  31697. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31698. var previousOne = previousSubmeshes[submeshIndex];
  31699. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31700. }
  31701. this.synchronizeInstances();
  31702. return this;
  31703. };
  31704. /**
  31705. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  31706. * In other words, more vertices, no more indices and a single bigger VBO.
  31707. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  31708. * Returns the Mesh.
  31709. */
  31710. Mesh.prototype.convertToUnIndexedMesh = function () {
  31711. /// <summary>Remove indices by unfolding faces into buffers</summary>
  31712. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31713. var kinds = this.getVerticesDataKinds();
  31714. var vbs = {};
  31715. var data = {};
  31716. var newdata = {};
  31717. var kindIndex;
  31718. var kind;
  31719. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31720. kind = kinds[kindIndex];
  31721. var vertexBuffer = this.getVertexBuffer(kind);
  31722. vbs[kind] = vertexBuffer;
  31723. data[kind] = vbs[kind].getData();
  31724. newdata[kind] = [];
  31725. }
  31726. // Save previous submeshes
  31727. var previousSubmeshes = this.subMeshes.slice(0);
  31728. var indices = this.getIndices();
  31729. var totalIndices = this.getTotalIndices();
  31730. // Generating unique vertices per face
  31731. var index;
  31732. for (index = 0; index < totalIndices; index++) {
  31733. var vertexIndex = indices[index];
  31734. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31735. kind = kinds[kindIndex];
  31736. var stride = vbs[kind].getStrideSize();
  31737. for (var offset = 0; offset < stride; offset++) {
  31738. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31739. }
  31740. }
  31741. }
  31742. // Updating indices
  31743. for (index = 0; index < totalIndices; index += 3) {
  31744. indices[index] = index;
  31745. indices[index + 1] = index + 1;
  31746. indices[index + 2] = index + 2;
  31747. }
  31748. this.setIndices(indices);
  31749. // Updating vertex buffers
  31750. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31751. kind = kinds[kindIndex];
  31752. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31753. }
  31754. // Updating submeshes
  31755. this.releaseSubMeshes();
  31756. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31757. var previousOne = previousSubmeshes[submeshIndex];
  31758. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31759. }
  31760. this._unIndexed = true;
  31761. this.synchronizeInstances();
  31762. return this;
  31763. };
  31764. /**
  31765. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  31766. * This method returns the Mesh.
  31767. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  31768. */
  31769. Mesh.prototype.flipFaces = function (flipNormals) {
  31770. if (flipNormals === void 0) { flipNormals = false; }
  31771. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  31772. var i;
  31773. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  31774. for (i = 0; i < vertex_data.normals.length; i++) {
  31775. vertex_data.normals[i] *= -1;
  31776. }
  31777. }
  31778. if (vertex_data.indices) {
  31779. var temp;
  31780. for (i = 0; i < vertex_data.indices.length; i += 3) {
  31781. // reassign indices
  31782. temp = vertex_data.indices[i + 1];
  31783. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  31784. vertex_data.indices[i + 2] = temp;
  31785. }
  31786. }
  31787. vertex_data.applyToMesh(this);
  31788. return this;
  31789. };
  31790. // Instances
  31791. /**
  31792. * Creates a new InstancedMesh object from the mesh model.
  31793. * An instance shares the same properties and the same material than its model.
  31794. * Only these properties of each instance can then be set individually :
  31795. * - position
  31796. * - rotation
  31797. * - rotationQuaternion
  31798. * - setPivotMatrix
  31799. * - scaling
  31800. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  31801. * Warning : this method is not supported for Line mesh and LineSystem
  31802. */
  31803. Mesh.prototype.createInstance = function (name) {
  31804. return new BABYLON.InstancedMesh(name, this);
  31805. };
  31806. /**
  31807. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  31808. * After this call, all the mesh instances have the same submeshes than the current mesh.
  31809. * This method returns the Mesh.
  31810. */
  31811. Mesh.prototype.synchronizeInstances = function () {
  31812. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  31813. var instance = this.instances[instanceIndex];
  31814. instance._syncSubMeshes();
  31815. }
  31816. return this;
  31817. };
  31818. /**
  31819. * Simplify the mesh according to the given array of settings.
  31820. * Function will return immediately and will simplify async. It returns the Mesh.
  31821. * @param settings a collection of simplification settings.
  31822. * @param parallelProcessing should all levels calculate parallel or one after the other.
  31823. * @param type the type of simplification to run.
  31824. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  31825. */
  31826. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  31827. if (parallelProcessing === void 0) { parallelProcessing = true; }
  31828. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  31829. this.getScene().simplificationQueue.addTask({
  31830. settings: settings,
  31831. parallelProcessing: parallelProcessing,
  31832. mesh: this,
  31833. simplificationType: simplificationType,
  31834. successCallback: successCallback
  31835. });
  31836. return this;
  31837. };
  31838. /**
  31839. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  31840. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  31841. * This should be used together with the simplification to avoid disappearing triangles.
  31842. * Returns the Mesh.
  31843. * @param successCallback an optional success callback to be called after the optimization finished.
  31844. */
  31845. Mesh.prototype.optimizeIndices = function (successCallback) {
  31846. var _this = this;
  31847. var indices = this.getIndices();
  31848. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31849. if (!positions || !indices) {
  31850. return this;
  31851. }
  31852. var vectorPositions = new Array();
  31853. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  31854. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  31855. }
  31856. var dupes = new Array();
  31857. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  31858. var realPos = vectorPositions.length - 1 - iteration;
  31859. var testedPosition = vectorPositions[realPos];
  31860. for (var j = 0; j < realPos; ++j) {
  31861. var againstPosition = vectorPositions[j];
  31862. if (testedPosition.equals(againstPosition)) {
  31863. dupes[realPos] = j;
  31864. break;
  31865. }
  31866. }
  31867. }, function () {
  31868. for (var i = 0; i < indices.length; ++i) {
  31869. indices[i] = dupes[indices[i]] || indices[i];
  31870. }
  31871. //indices are now reordered
  31872. var originalSubMeshes = _this.subMeshes.slice(0);
  31873. _this.setIndices(indices);
  31874. _this.subMeshes = originalSubMeshes;
  31875. if (successCallback) {
  31876. successCallback(_this);
  31877. }
  31878. });
  31879. return this;
  31880. };
  31881. Mesh.prototype.serialize = function (serializationObject) {
  31882. serializationObject.name = this.name;
  31883. serializationObject.id = this.id;
  31884. serializationObject.type = this.getClassName();
  31885. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31886. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31887. }
  31888. serializationObject.position = this.position.asArray();
  31889. if (this.rotationQuaternion) {
  31890. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  31891. }
  31892. else if (this.rotation) {
  31893. serializationObject.rotation = this.rotation.asArray();
  31894. }
  31895. serializationObject.scaling = this.scaling.asArray();
  31896. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  31897. serializationObject.isEnabled = this.isEnabled(false);
  31898. serializationObject.isVisible = this.isVisible;
  31899. serializationObject.infiniteDistance = this.infiniteDistance;
  31900. serializationObject.pickable = this.isPickable;
  31901. serializationObject.receiveShadows = this.receiveShadows;
  31902. serializationObject.billboardMode = this.billboardMode;
  31903. serializationObject.visibility = this.visibility;
  31904. serializationObject.checkCollisions = this.checkCollisions;
  31905. serializationObject.isBlocker = this.isBlocker;
  31906. // Parent
  31907. if (this.parent) {
  31908. serializationObject.parentId = this.parent.id;
  31909. }
  31910. // Geometry
  31911. serializationObject.isUnIndexed = this.isUnIndexed;
  31912. var geometry = this._geometry;
  31913. if (geometry) {
  31914. var geometryId = geometry.id;
  31915. serializationObject.geometryId = geometryId;
  31916. // SubMeshes
  31917. serializationObject.subMeshes = [];
  31918. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  31919. var subMesh = this.subMeshes[subIndex];
  31920. serializationObject.subMeshes.push({
  31921. materialIndex: subMesh.materialIndex,
  31922. verticesStart: subMesh.verticesStart,
  31923. verticesCount: subMesh.verticesCount,
  31924. indexStart: subMesh.indexStart,
  31925. indexCount: subMesh.indexCount
  31926. });
  31927. }
  31928. }
  31929. // Material
  31930. if (this.material) {
  31931. serializationObject.materialId = this.material.id;
  31932. }
  31933. else {
  31934. this.material = null;
  31935. }
  31936. // Morph targets
  31937. if (this.morphTargetManager) {
  31938. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  31939. }
  31940. // Skeleton
  31941. if (this.skeleton) {
  31942. serializationObject.skeletonId = this.skeleton.id;
  31943. }
  31944. // Physics
  31945. //TODO implement correct serialization for physics impostors.
  31946. var impostor = this.getPhysicsImpostor();
  31947. if (impostor) {
  31948. serializationObject.physicsMass = impostor.getParam("mass");
  31949. serializationObject.physicsFriction = impostor.getParam("friction");
  31950. serializationObject.physicsRestitution = impostor.getParam("mass");
  31951. serializationObject.physicsImpostor = impostor.type;
  31952. }
  31953. // Metadata
  31954. if (this.metadata) {
  31955. serializationObject.metadata = this.metadata;
  31956. }
  31957. // Instances
  31958. serializationObject.instances = [];
  31959. for (var index = 0; index < this.instances.length; index++) {
  31960. var instance = this.instances[index];
  31961. var serializationInstance = {
  31962. name: instance.name,
  31963. id: instance.id,
  31964. position: instance.position.asArray(),
  31965. scaling: instance.scaling.asArray()
  31966. };
  31967. if (instance.rotationQuaternion) {
  31968. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31969. }
  31970. else if (instance.rotation) {
  31971. serializationInstance.rotation = instance.rotation.asArray();
  31972. }
  31973. serializationObject.instances.push(serializationInstance);
  31974. // Animations
  31975. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31976. serializationInstance.ranges = instance.serializeAnimationRanges();
  31977. }
  31978. //
  31979. // Animations
  31980. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31981. serializationObject.ranges = this.serializeAnimationRanges();
  31982. // Layer mask
  31983. serializationObject.layerMask = this.layerMask;
  31984. // Alpha
  31985. serializationObject.alphaIndex = this.alphaIndex;
  31986. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  31987. // Overlay
  31988. serializationObject.overlayAlpha = this.overlayAlpha;
  31989. serializationObject.overlayColor = this.overlayColor.asArray();
  31990. serializationObject.renderOverlay = this.renderOverlay;
  31991. // Fog
  31992. serializationObject.applyFog = this.applyFog;
  31993. // Action Manager
  31994. if (this.actionManager) {
  31995. serializationObject.actions = this.actionManager.serialize(this.name);
  31996. }
  31997. };
  31998. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  31999. if (!this.geometry) {
  32000. return;
  32001. }
  32002. this._markSubMeshesAsAttributesDirty();
  32003. var morphTargetManager = this._morphTargetManager;
  32004. if (morphTargetManager && morphTargetManager.vertexCount) {
  32005. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32006. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32007. this.morphTargetManager = null;
  32008. return;
  32009. }
  32010. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32011. var morphTarget = morphTargetManager.getActiveTarget(index);
  32012. var positions = morphTarget.getPositions();
  32013. if (!positions) {
  32014. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32015. return;
  32016. }
  32017. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32018. var normals = morphTarget.getNormals();
  32019. if (normals) {
  32020. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32021. }
  32022. var tangents = morphTarget.getTangents();
  32023. if (tangents) {
  32024. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32025. }
  32026. }
  32027. }
  32028. else {
  32029. var index = 0;
  32030. // Positions
  32031. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32032. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32033. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32034. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32035. }
  32036. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32037. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32038. }
  32039. index++;
  32040. }
  32041. }
  32042. };
  32043. // Statics
  32044. /**
  32045. * Returns a new Mesh object parsed from the source provided.
  32046. * The parameter `parsedMesh` is the source.
  32047. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32048. */
  32049. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32050. var mesh;
  32051. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32052. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32053. }
  32054. else {
  32055. mesh = new Mesh(parsedMesh.name, scene);
  32056. }
  32057. mesh.id = parsedMesh.id;
  32058. if (BABYLON.Tags) {
  32059. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32060. }
  32061. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32062. if (parsedMesh.metadata !== undefined) {
  32063. mesh.metadata = parsedMesh.metadata;
  32064. }
  32065. if (parsedMesh.rotationQuaternion) {
  32066. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32067. }
  32068. else if (parsedMesh.rotation) {
  32069. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32070. }
  32071. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32072. if (parsedMesh.localMatrix) {
  32073. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32074. }
  32075. else if (parsedMesh.pivotMatrix) {
  32076. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32077. }
  32078. mesh.setEnabled(parsedMesh.isEnabled);
  32079. mesh.isVisible = parsedMesh.isVisible;
  32080. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32081. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32082. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32083. if (parsedMesh.applyFog !== undefined) {
  32084. mesh.applyFog = parsedMesh.applyFog;
  32085. }
  32086. if (parsedMesh.pickable !== undefined) {
  32087. mesh.isPickable = parsedMesh.pickable;
  32088. }
  32089. if (parsedMesh.alphaIndex !== undefined) {
  32090. mesh.alphaIndex = parsedMesh.alphaIndex;
  32091. }
  32092. mesh.receiveShadows = parsedMesh.receiveShadows;
  32093. mesh.billboardMode = parsedMesh.billboardMode;
  32094. if (parsedMesh.visibility !== undefined) {
  32095. mesh.visibility = parsedMesh.visibility;
  32096. }
  32097. mesh.checkCollisions = parsedMesh.checkCollisions;
  32098. if (parsedMesh.isBlocker !== undefined) {
  32099. mesh.isBlocker = parsedMesh.isBlocker;
  32100. }
  32101. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32102. // freezeWorldMatrix
  32103. if (parsedMesh.freezeWorldMatrix) {
  32104. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32105. }
  32106. // Parent
  32107. if (parsedMesh.parentId) {
  32108. mesh._waitingParentId = parsedMesh.parentId;
  32109. }
  32110. // Actions
  32111. if (parsedMesh.actions !== undefined) {
  32112. mesh._waitingActions = parsedMesh.actions;
  32113. }
  32114. // Overlay
  32115. if (parsedMesh.overlayAlpha !== undefined) {
  32116. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32117. }
  32118. if (parsedMesh.overlayColor !== undefined) {
  32119. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32120. }
  32121. if (parsedMesh.renderOverlay !== undefined) {
  32122. mesh.renderOverlay = parsedMesh.renderOverlay;
  32123. }
  32124. // Geometry
  32125. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32126. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32127. if (parsedMesh.delayLoadingFile) {
  32128. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32129. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32130. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32131. if (parsedMesh._binaryInfo) {
  32132. mesh._binaryInfo = parsedMesh._binaryInfo;
  32133. }
  32134. mesh._delayInfo = [];
  32135. if (parsedMesh.hasUVs) {
  32136. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32137. }
  32138. if (parsedMesh.hasUVs2) {
  32139. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32140. }
  32141. if (parsedMesh.hasUVs3) {
  32142. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32143. }
  32144. if (parsedMesh.hasUVs4) {
  32145. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32146. }
  32147. if (parsedMesh.hasUVs5) {
  32148. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32149. }
  32150. if (parsedMesh.hasUVs6) {
  32151. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32152. }
  32153. if (parsedMesh.hasColors) {
  32154. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32155. }
  32156. if (parsedMesh.hasMatricesIndices) {
  32157. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32158. }
  32159. if (parsedMesh.hasMatricesWeights) {
  32160. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32161. }
  32162. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32163. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32164. mesh._checkDelayState();
  32165. }
  32166. }
  32167. else {
  32168. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32169. }
  32170. // Material
  32171. if (parsedMesh.materialId) {
  32172. mesh.setMaterialByID(parsedMesh.materialId);
  32173. }
  32174. else {
  32175. mesh.material = null;
  32176. }
  32177. // Morph targets
  32178. if (parsedMesh.morphTargetManagerId > -1) {
  32179. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32180. }
  32181. // Skeleton
  32182. if (parsedMesh.skeletonId > -1) {
  32183. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32184. if (parsedMesh.numBoneInfluencers) {
  32185. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32186. }
  32187. }
  32188. // Animations
  32189. if (parsedMesh.animations) {
  32190. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32191. var parsedAnimation = parsedMesh.animations[animationIndex];
  32192. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32193. }
  32194. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32195. }
  32196. if (parsedMesh.autoAnimate) {
  32197. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32198. }
  32199. // Layer Mask
  32200. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32201. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32202. }
  32203. else {
  32204. mesh.layerMask = 0x0FFFFFFF;
  32205. }
  32206. // Physics
  32207. if (parsedMesh.physicsImpostor) {
  32208. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32209. mass: parsedMesh.physicsMass,
  32210. friction: parsedMesh.physicsFriction,
  32211. restitution: parsedMesh.physicsRestitution
  32212. }, scene);
  32213. }
  32214. // Instances
  32215. if (parsedMesh.instances) {
  32216. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32217. var parsedInstance = parsedMesh.instances[index];
  32218. var instance = mesh.createInstance(parsedInstance.name);
  32219. if (parsedInstance.id) {
  32220. instance.id = parsedInstance.id;
  32221. }
  32222. if (BABYLON.Tags) {
  32223. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32224. }
  32225. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32226. if (parsedInstance.parentId) {
  32227. instance._waitingParentId = parsedInstance.parentId;
  32228. }
  32229. if (parsedInstance.rotationQuaternion) {
  32230. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32231. }
  32232. else if (parsedInstance.rotation) {
  32233. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32234. }
  32235. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32236. instance.checkCollisions = mesh.checkCollisions;
  32237. if (parsedMesh.animations) {
  32238. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32239. parsedAnimation = parsedMesh.animations[animationIndex];
  32240. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32241. }
  32242. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32243. }
  32244. }
  32245. }
  32246. return mesh;
  32247. };
  32248. /**
  32249. * Creates a ribbon mesh.
  32250. * Please consider using the same method from the MeshBuilder class instead.
  32251. * 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.
  32252. *
  32253. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32254. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32255. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32256. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32257. * 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.
  32258. * 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.
  32259. * 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
  32260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32263. */
  32264. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32265. if (closeArray === void 0) { closeArray = false; }
  32266. if (updatable === void 0) { updatable = false; }
  32267. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32268. pathArray: pathArray,
  32269. closeArray: closeArray,
  32270. closePath: closePath,
  32271. offset: offset,
  32272. updatable: updatable,
  32273. sideOrientation: sideOrientation,
  32274. instance: instance
  32275. }, scene);
  32276. };
  32277. /**
  32278. * Creates a plane polygonal mesh. By default, this is a disc.
  32279. * Please consider using the same method from the MeshBuilder class instead.
  32280. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32281. * 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.
  32282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32285. */
  32286. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32287. if (scene === void 0) { scene = null; }
  32288. var options = {
  32289. radius: radius,
  32290. tessellation: tessellation,
  32291. sideOrientation: sideOrientation,
  32292. updatable: updatable
  32293. };
  32294. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32295. };
  32296. /**
  32297. * Creates a box mesh.
  32298. * Please consider using the same method from the MeshBuilder class instead.
  32299. * The parameter `size` sets the size (float) of each box side (default 1).
  32300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32303. */
  32304. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32305. if (scene === void 0) { scene = null; }
  32306. var options = {
  32307. size: size,
  32308. sideOrientation: sideOrientation,
  32309. updatable: updatable
  32310. };
  32311. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32312. };
  32313. /**
  32314. * Creates a sphere mesh.
  32315. * Please consider using the same method from the MeshBuilder class instead.
  32316. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32317. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32321. */
  32322. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32323. var options = {
  32324. segments: segments,
  32325. diameterX: diameter,
  32326. diameterY: diameter,
  32327. diameterZ: diameter,
  32328. sideOrientation: sideOrientation,
  32329. updatable: updatable
  32330. };
  32331. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32332. };
  32333. /**
  32334. * Creates a cylinder or a cone mesh.
  32335. * Please consider using the same method from the MeshBuilder class instead.
  32336. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32337. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32338. * 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.
  32339. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32340. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32344. */
  32345. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32346. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32347. if (scene !== undefined) {
  32348. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32349. updatable = scene;
  32350. }
  32351. scene = subdivisions;
  32352. subdivisions = 1;
  32353. }
  32354. var options = {
  32355. height: height,
  32356. diameterTop: diameterTop,
  32357. diameterBottom: diameterBottom,
  32358. tessellation: tessellation,
  32359. subdivisions: subdivisions,
  32360. sideOrientation: sideOrientation,
  32361. updatable: updatable
  32362. };
  32363. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32364. };
  32365. // Torus (Code from SharpDX.org)
  32366. /**
  32367. * Creates a torus mesh.
  32368. * Please consider using the same method from the MeshBuilder class instead.
  32369. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32370. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32371. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32375. */
  32376. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32377. var options = {
  32378. diameter: diameter,
  32379. thickness: thickness,
  32380. tessellation: tessellation,
  32381. sideOrientation: sideOrientation,
  32382. updatable: updatable
  32383. };
  32384. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32385. };
  32386. /**
  32387. * Creates a torus knot mesh.
  32388. * Please consider using the same method from the MeshBuilder class instead.
  32389. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32390. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32391. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32392. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32396. */
  32397. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32398. var options = {
  32399. radius: radius,
  32400. tube: tube,
  32401. radialSegments: radialSegments,
  32402. tubularSegments: tubularSegments,
  32403. p: p,
  32404. q: q,
  32405. sideOrientation: sideOrientation,
  32406. updatable: updatable
  32407. };
  32408. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32409. };
  32410. /**
  32411. * Creates a line mesh.
  32412. * Please consider using the same method from the MeshBuilder class instead.
  32413. * 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.
  32414. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32415. * The parameter `points` is an array successive Vector3.
  32416. * 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
  32417. * When updating an instance, remember that only point positions can change, not the number of points.
  32418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32419. */
  32420. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32421. if (scene === void 0) { scene = null; }
  32422. if (updatable === void 0) { updatable = false; }
  32423. if (instance === void 0) { instance = null; }
  32424. var options = {
  32425. points: points,
  32426. updatable: updatable,
  32427. instance: instance
  32428. };
  32429. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32430. };
  32431. /**
  32432. * Creates a dashed line mesh.
  32433. * Please consider using the same method from the MeshBuilder class instead.
  32434. * 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.
  32435. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32436. * The parameter `points` is an array successive Vector3.
  32437. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32438. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32439. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32440. * 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
  32441. * When updating an instance, remember that only point positions can change, not the number of points.
  32442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32443. */
  32444. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32445. if (scene === void 0) { scene = null; }
  32446. var options = {
  32447. points: points,
  32448. dashSize: dashSize,
  32449. gapSize: gapSize,
  32450. dashNb: dashNb,
  32451. updatable: updatable,
  32452. instance: instance
  32453. };
  32454. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32455. };
  32456. /**
  32457. * Creates a polygon mesh.
  32458. * Please consider using the same method from the MeshBuilder class instead.
  32459. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32460. * 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.
  32461. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32463. * Remember you can only change the shape positions, not their number when updating a polygon.
  32464. */
  32465. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32466. var options = {
  32467. shape: shape,
  32468. holes: holes,
  32469. updatable: updatable,
  32470. sideOrientation: sideOrientation
  32471. };
  32472. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32473. };
  32474. /**
  32475. * Creates an extruded polygon mesh, with depth in the Y direction.
  32476. * Please consider using the same method from the MeshBuilder class instead.
  32477. */
  32478. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32479. var options = {
  32480. shape: shape,
  32481. holes: holes,
  32482. depth: depth,
  32483. updatable: updatable,
  32484. sideOrientation: sideOrientation
  32485. };
  32486. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32487. };
  32488. /**
  32489. * Creates an extruded shape mesh.
  32490. * 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.
  32491. * Please consider using the same method from the MeshBuilder class instead.
  32492. *
  32493. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32494. * 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
  32495. * extruded along the Z axis.
  32496. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32497. * 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.
  32498. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32499. * 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
  32500. * 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
  32501. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32505. */
  32506. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32507. if (scene === void 0) { scene = null; }
  32508. var options = {
  32509. shape: shape,
  32510. path: path,
  32511. scale: scale,
  32512. rotation: rotation,
  32513. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32514. sideOrientation: sideOrientation,
  32515. instance: instance,
  32516. updatable: updatable
  32517. };
  32518. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32519. };
  32520. /**
  32521. * Creates an custom extruded shape mesh.
  32522. * 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.
  32523. * Please consider using the same method from the MeshBuilder class instead.
  32524. *
  32525. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32526. * 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
  32527. * extruded along the Z axis.
  32528. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32529. * 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
  32530. * and the distance of this point from the begining of the path :
  32531. * ```javascript
  32532. * var rotationFunction = function(i, distance) {
  32533. * // do things
  32534. * return rotationValue; }
  32535. * ```
  32536. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32537. * 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
  32538. * and the distance of this point from the begining of the path :
  32539. * ```javascript
  32540. * var scaleFunction = function(i, distance) {
  32541. * // do things
  32542. * return scaleValue;}
  32543. * ```
  32544. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32545. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32546. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32547. * 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
  32548. * 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
  32549. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32553. */
  32554. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32555. var options = {
  32556. shape: shape,
  32557. path: path,
  32558. scaleFunction: scaleFunction,
  32559. rotationFunction: rotationFunction,
  32560. ribbonCloseArray: ribbonCloseArray,
  32561. ribbonClosePath: ribbonClosePath,
  32562. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32563. sideOrientation: sideOrientation,
  32564. instance: instance,
  32565. updatable: updatable
  32566. };
  32567. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32568. };
  32569. /**
  32570. * Creates lathe mesh.
  32571. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32572. * Please consider using the same method from the MeshBuilder class instead.
  32573. * 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
  32574. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32575. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32576. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32580. */
  32581. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32582. var options = {
  32583. shape: shape,
  32584. radius: radius,
  32585. tessellation: tessellation,
  32586. sideOrientation: sideOrientation,
  32587. updatable: updatable
  32588. };
  32589. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32590. };
  32591. /**
  32592. * Creates a plane mesh.
  32593. * Please consider using the same method from the MeshBuilder class instead.
  32594. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32595. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32598. */
  32599. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32600. var options = {
  32601. size: size,
  32602. width: size,
  32603. height: size,
  32604. sideOrientation: sideOrientation,
  32605. updatable: updatable
  32606. };
  32607. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32608. };
  32609. /**
  32610. * Creates a ground mesh.
  32611. * Please consider using the same method from the MeshBuilder class instead.
  32612. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32613. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32615. */
  32616. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32617. var options = {
  32618. width: width,
  32619. height: height,
  32620. subdivisions: subdivisions,
  32621. updatable: updatable
  32622. };
  32623. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32624. };
  32625. /**
  32626. * Creates a tiled ground mesh.
  32627. * Please consider using the same method from the MeshBuilder class instead.
  32628. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32629. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32630. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32631. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32632. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32633. * numbers of subdivisions on the ground width and height of each tile.
  32634. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32635. */
  32636. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32637. var options = {
  32638. xmin: xmin,
  32639. zmin: zmin,
  32640. xmax: xmax,
  32641. zmax: zmax,
  32642. subdivisions: subdivisions,
  32643. precision: precision,
  32644. updatable: updatable
  32645. };
  32646. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32647. };
  32648. /**
  32649. * Creates a ground mesh from a height map.
  32650. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32651. * Please consider using the same method from the MeshBuilder class instead.
  32652. * The parameter `url` sets the URL of the height map image resource.
  32653. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  32654. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  32655. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  32656. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  32657. * 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).
  32658. * This function is passed the newly built mesh :
  32659. * ```javascript
  32660. * function(mesh) { // do things
  32661. * return; }
  32662. * ```
  32663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32664. */
  32665. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  32666. var options = {
  32667. width: width,
  32668. height: height,
  32669. subdivisions: subdivisions,
  32670. minHeight: minHeight,
  32671. maxHeight: maxHeight,
  32672. updatable: updatable,
  32673. onReady: onReady
  32674. };
  32675. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  32676. };
  32677. /**
  32678. * Creates a tube mesh.
  32679. * 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.
  32680. * Please consider using the same method from the MeshBuilder class instead.
  32681. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  32682. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  32683. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  32684. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  32685. * 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.
  32686. * It must return a radius value (positive float) :
  32687. * ```javascript
  32688. * var radiusFunction = function(i, distance) {
  32689. * // do things
  32690. * return radius; }
  32691. * ```
  32692. * 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
  32693. * 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
  32694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32695. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32697. */
  32698. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  32699. var options = {
  32700. path: path,
  32701. radius: radius,
  32702. tessellation: tessellation,
  32703. radiusFunction: radiusFunction,
  32704. arc: 1,
  32705. cap: cap,
  32706. updatable: updatable,
  32707. sideOrientation: sideOrientation,
  32708. instance: instance
  32709. };
  32710. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  32711. };
  32712. /**
  32713. * Creates a polyhedron mesh.
  32714. * Please consider using the same method from the MeshBuilder class instead.
  32715. * 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
  32716. * to choose the wanted type.
  32717. * The parameter `size` (positive float, default 1) sets the polygon size.
  32718. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  32719. * 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`.
  32720. * 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
  32721. * 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)`).
  32722. * 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
  32723. * 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.
  32724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32725. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32727. */
  32728. Mesh.CreatePolyhedron = function (name, options, scene) {
  32729. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  32730. };
  32731. /**
  32732. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  32733. * Please consider using the same method from the MeshBuilder class instead.
  32734. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  32735. * 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`).
  32736. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  32737. * 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.
  32738. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32739. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32740. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32741. */
  32742. Mesh.CreateIcoSphere = function (name, options, scene) {
  32743. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  32744. };
  32745. /**
  32746. * Creates a decal mesh.
  32747. * Please consider using the same method from the MeshBuilder class instead.
  32748. * 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.
  32749. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  32750. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  32751. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  32752. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  32753. */
  32754. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  32755. var options = {
  32756. position: position,
  32757. normal: normal,
  32758. size: size,
  32759. angle: angle
  32760. };
  32761. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  32762. };
  32763. // Skeletons
  32764. /**
  32765. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  32766. */
  32767. Mesh.prototype.setPositionsForCPUSkinning = function () {
  32768. if (!this._sourcePositions) {
  32769. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32770. if (!source) {
  32771. return this._sourcePositions;
  32772. }
  32773. this._sourcePositions = new Float32Array(source);
  32774. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32775. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  32776. }
  32777. }
  32778. return this._sourcePositions;
  32779. };
  32780. /**
  32781. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  32782. */
  32783. Mesh.prototype.setNormalsForCPUSkinning = function () {
  32784. if (!this._sourceNormals) {
  32785. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32786. if (!source) {
  32787. return this._sourceNormals;
  32788. }
  32789. this._sourceNormals = new Float32Array(source);
  32790. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32791. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  32792. }
  32793. }
  32794. return this._sourceNormals;
  32795. };
  32796. /**
  32797. * Updates the vertex buffer by applying transformation from the bones.
  32798. * Returns the Mesh.
  32799. *
  32800. * @param {skeleton} skeleton to apply
  32801. */
  32802. Mesh.prototype.applySkeleton = function (skeleton) {
  32803. if (!this.geometry) {
  32804. return this;
  32805. }
  32806. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  32807. return this;
  32808. }
  32809. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  32810. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32811. return this;
  32812. }
  32813. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32814. return this;
  32815. }
  32816. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32817. return this;
  32818. }
  32819. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32820. return this;
  32821. }
  32822. if (!this._sourcePositions) {
  32823. var submeshes = this.subMeshes.slice();
  32824. this.setPositionsForCPUSkinning();
  32825. this.subMeshes = submeshes;
  32826. }
  32827. if (!this._sourceNormals) {
  32828. this.setNormalsForCPUSkinning();
  32829. }
  32830. // positionsData checks for not being Float32Array will only pass at most once
  32831. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32832. if (!positionsData) {
  32833. return this;
  32834. }
  32835. if (!(positionsData instanceof Float32Array)) {
  32836. positionsData = new Float32Array(positionsData);
  32837. }
  32838. // normalsData checks for not being Float32Array will only pass at most once
  32839. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32840. if (!normalsData) {
  32841. return this;
  32842. }
  32843. if (!(normalsData instanceof Float32Array)) {
  32844. normalsData = new Float32Array(normalsData);
  32845. }
  32846. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32847. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32848. if (!matricesWeightsData || !matricesIndicesData) {
  32849. return this;
  32850. }
  32851. var needExtras = this.numBoneInfluencers > 4;
  32852. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32853. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32854. var skeletonMatrices = skeleton.getTransformMatrices(this);
  32855. var tempVector3 = BABYLON.Vector3.Zero();
  32856. var finalMatrix = new BABYLON.Matrix();
  32857. var tempMatrix = new BABYLON.Matrix();
  32858. var matWeightIdx = 0;
  32859. var inf;
  32860. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  32861. var weight;
  32862. for (inf = 0; inf < 4; inf++) {
  32863. weight = matricesWeightsData[matWeightIdx + inf];
  32864. if (weight > 0) {
  32865. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32866. finalMatrix.addToSelf(tempMatrix);
  32867. }
  32868. else
  32869. break;
  32870. }
  32871. if (needExtras) {
  32872. for (inf = 0; inf < 4; inf++) {
  32873. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32874. if (weight > 0) {
  32875. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32876. finalMatrix.addToSelf(tempMatrix);
  32877. }
  32878. else
  32879. break;
  32880. }
  32881. }
  32882. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  32883. tempVector3.toArray(positionsData, index);
  32884. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  32885. tempVector3.toArray(normalsData, index);
  32886. finalMatrix.reset();
  32887. }
  32888. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  32889. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  32890. return this;
  32891. };
  32892. // Tools
  32893. /**
  32894. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  32895. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  32896. */
  32897. Mesh.MinMax = function (meshes) {
  32898. var minVector = null;
  32899. var maxVector = null;
  32900. meshes.forEach(function (mesh, index, array) {
  32901. var boundingInfo = mesh.getBoundingInfo();
  32902. var boundingBox = boundingInfo.boundingBox;
  32903. if (!minVector || !maxVector) {
  32904. minVector = boundingBox.minimumWorld;
  32905. maxVector = boundingBox.maximumWorld;
  32906. }
  32907. else {
  32908. minVector.minimizeInPlace(boundingBox.minimumWorld);
  32909. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  32910. }
  32911. });
  32912. if (!minVector || !maxVector) {
  32913. return {
  32914. min: BABYLON.Vector3.Zero(),
  32915. max: BABYLON.Vector3.Zero()
  32916. };
  32917. }
  32918. return {
  32919. min: minVector,
  32920. max: maxVector
  32921. };
  32922. };
  32923. /**
  32924. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  32925. */
  32926. Mesh.Center = function (meshesOrMinMaxVector) {
  32927. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  32928. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  32929. };
  32930. /**
  32931. * Merge the array of meshes into a single mesh for performance reasons.
  32932. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  32933. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  32934. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  32935. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  32936. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  32937. */
  32938. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  32939. if (disposeSource === void 0) { disposeSource = true; }
  32940. var index;
  32941. if (!allow32BitsIndices) {
  32942. var totalVertices = 0;
  32943. // Counting vertices
  32944. for (index = 0; index < meshes.length; index++) {
  32945. if (meshes[index]) {
  32946. totalVertices += meshes[index].getTotalVertices();
  32947. if (totalVertices > 65536) {
  32948. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  32949. return null;
  32950. }
  32951. }
  32952. }
  32953. }
  32954. // Merge
  32955. var vertexData = null;
  32956. var otherVertexData;
  32957. var indiceArray = new Array();
  32958. var source = null;
  32959. for (index = 0; index < meshes.length; index++) {
  32960. if (meshes[index]) {
  32961. meshes[index].computeWorldMatrix(true);
  32962. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  32963. otherVertexData.transform(meshes[index].getWorldMatrix());
  32964. if (vertexData) {
  32965. vertexData.merge(otherVertexData);
  32966. }
  32967. else {
  32968. vertexData = otherVertexData;
  32969. source = meshes[index];
  32970. }
  32971. if (subdivideWithSubMeshes) {
  32972. indiceArray.push(meshes[index].getTotalIndices());
  32973. }
  32974. }
  32975. }
  32976. source = source;
  32977. if (!meshSubclass) {
  32978. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  32979. }
  32980. vertexData.applyToMesh(meshSubclass);
  32981. // Setting properties
  32982. meshSubclass.material = source.material;
  32983. meshSubclass.checkCollisions = source.checkCollisions;
  32984. // Cleaning
  32985. if (disposeSource) {
  32986. for (index = 0; index < meshes.length; index++) {
  32987. if (meshes[index]) {
  32988. meshes[index].dispose();
  32989. }
  32990. }
  32991. }
  32992. // Subdivide
  32993. if (subdivideWithSubMeshes) {
  32994. //-- Suppresions du submesh global
  32995. meshSubclass.releaseSubMeshes();
  32996. index = 0;
  32997. var offset = 0;
  32998. //-- aplique la subdivision en fonction du tableau d'indices
  32999. while (index < indiceArray.length) {
  33000. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33001. offset += indiceArray[index];
  33002. index++;
  33003. }
  33004. }
  33005. return meshSubclass;
  33006. };
  33007. // Consts
  33008. Mesh._FRONTSIDE = 0;
  33009. Mesh._BACKSIDE = 1;
  33010. Mesh._DOUBLESIDE = 2;
  33011. Mesh._DEFAULTSIDE = 0;
  33012. Mesh._NO_CAP = 0;
  33013. Mesh._CAP_START = 1;
  33014. Mesh._CAP_END = 2;
  33015. Mesh._CAP_ALL = 3;
  33016. return Mesh;
  33017. }(BABYLON.AbstractMesh));
  33018. BABYLON.Mesh = Mesh;
  33019. })(BABYLON || (BABYLON = {}));
  33020. //# sourceMappingURL=babylon.mesh.js.map
  33021. "use strict";
  33022. var BABYLON;
  33023. (function (BABYLON) {
  33024. var BaseSubMesh = /** @class */ (function () {
  33025. function BaseSubMesh() {
  33026. }
  33027. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33028. get: function () {
  33029. return this._materialEffect;
  33030. },
  33031. enumerable: true,
  33032. configurable: true
  33033. });
  33034. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33035. if (defines === void 0) { defines = null; }
  33036. if (this._materialEffect === effect) {
  33037. if (!effect) {
  33038. this._materialDefines = null;
  33039. }
  33040. return;
  33041. }
  33042. this._materialDefines = defines;
  33043. this._materialEffect = effect;
  33044. };
  33045. return BaseSubMesh;
  33046. }());
  33047. BABYLON.BaseSubMesh = BaseSubMesh;
  33048. var SubMesh = /** @class */ (function (_super) {
  33049. __extends(SubMesh, _super);
  33050. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33051. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33052. var _this = _super.call(this) || this;
  33053. _this.materialIndex = materialIndex;
  33054. _this.verticesStart = verticesStart;
  33055. _this.verticesCount = verticesCount;
  33056. _this.indexStart = indexStart;
  33057. _this.indexCount = indexCount;
  33058. _this._renderId = 0;
  33059. _this._mesh = mesh;
  33060. _this._renderingMesh = renderingMesh || mesh;
  33061. mesh.subMeshes.push(_this);
  33062. _this._trianglePlanes = [];
  33063. _this._id = mesh.subMeshes.length - 1;
  33064. if (createBoundingBox) {
  33065. _this.refreshBoundingInfo();
  33066. mesh.computeWorldMatrix(true);
  33067. }
  33068. return _this;
  33069. }
  33070. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33071. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33072. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33073. };
  33074. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33075. get: function () {
  33076. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33077. },
  33078. enumerable: true,
  33079. configurable: true
  33080. });
  33081. /**
  33082. * Returns the submesh BoudingInfo object.
  33083. */
  33084. SubMesh.prototype.getBoundingInfo = function () {
  33085. if (this.IsGlobal) {
  33086. return this._mesh.getBoundingInfo();
  33087. }
  33088. return this._boundingInfo;
  33089. };
  33090. /**
  33091. * Sets the submesh BoundingInfo.
  33092. * Return the SubMesh.
  33093. */
  33094. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33095. this._boundingInfo = boundingInfo;
  33096. return this;
  33097. };
  33098. /**
  33099. * Returns the mesh of the current submesh.
  33100. */
  33101. SubMesh.prototype.getMesh = function () {
  33102. return this._mesh;
  33103. };
  33104. /**
  33105. * Returns the rendering mesh of the submesh.
  33106. */
  33107. SubMesh.prototype.getRenderingMesh = function () {
  33108. return this._renderingMesh;
  33109. };
  33110. /**
  33111. * Returns the submesh material.
  33112. */
  33113. SubMesh.prototype.getMaterial = function () {
  33114. var rootMaterial = this._renderingMesh.material;
  33115. if (rootMaterial === null || rootMaterial === undefined) {
  33116. return this._mesh.getScene().defaultMaterial;
  33117. }
  33118. else if (rootMaterial.getSubMaterial) {
  33119. var multiMaterial = rootMaterial;
  33120. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33121. if (this._currentMaterial !== effectiveMaterial) {
  33122. this._currentMaterial = effectiveMaterial;
  33123. this._materialDefines = null;
  33124. }
  33125. return effectiveMaterial;
  33126. }
  33127. return rootMaterial;
  33128. };
  33129. // Methods
  33130. /**
  33131. * Sets a new updated BoundingInfo object to the submesh.
  33132. * Returns the SubMesh.
  33133. */
  33134. SubMesh.prototype.refreshBoundingInfo = function () {
  33135. this._lastColliderWorldVertices = null;
  33136. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33137. return this;
  33138. }
  33139. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33140. if (!data) {
  33141. this._boundingInfo = this._mesh.getBoundingInfo();
  33142. return this;
  33143. }
  33144. var indices = this._renderingMesh.getIndices();
  33145. var extend;
  33146. //is this the only submesh?
  33147. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33148. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33149. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33150. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33151. }
  33152. else {
  33153. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33154. }
  33155. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33156. return this;
  33157. };
  33158. SubMesh.prototype._checkCollision = function (collider) {
  33159. var boundingInfo = this.getBoundingInfo();
  33160. return boundingInfo._checkCollision(collider);
  33161. };
  33162. /**
  33163. * Updates the submesh BoundingInfo.
  33164. * Returns the Submesh.
  33165. */
  33166. SubMesh.prototype.updateBoundingInfo = function (world) {
  33167. var boundingInfo = this.getBoundingInfo();
  33168. if (!boundingInfo) {
  33169. this.refreshBoundingInfo();
  33170. boundingInfo = this.getBoundingInfo();
  33171. }
  33172. boundingInfo.update(world);
  33173. return this;
  33174. };
  33175. /**
  33176. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33177. * Boolean returned.
  33178. */
  33179. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33180. var boundingInfo = this.getBoundingInfo();
  33181. if (!boundingInfo) {
  33182. return false;
  33183. }
  33184. return boundingInfo.isInFrustum(frustumPlanes);
  33185. };
  33186. /**
  33187. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33188. * Boolean returned.
  33189. */
  33190. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33191. var boundingInfo = this.getBoundingInfo();
  33192. if (!boundingInfo) {
  33193. return false;
  33194. }
  33195. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33196. };
  33197. /**
  33198. * Renders the submesh.
  33199. * Returns it.
  33200. */
  33201. SubMesh.prototype.render = function (enableAlphaMode) {
  33202. this._renderingMesh.render(this, enableAlphaMode);
  33203. return this;
  33204. };
  33205. /**
  33206. * Returns a new Index Buffer.
  33207. * Type returned : WebGLBuffer.
  33208. */
  33209. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33210. if (!this._linesIndexBuffer) {
  33211. var linesIndices = [];
  33212. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33213. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33214. }
  33215. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33216. this.linesIndexCount = linesIndices.length;
  33217. }
  33218. return this._linesIndexBuffer;
  33219. };
  33220. /**
  33221. * True is the passed Ray intersects the submesh bounding box.
  33222. * Boolean returned.
  33223. */
  33224. SubMesh.prototype.canIntersects = function (ray) {
  33225. var boundingInfo = this.getBoundingInfo();
  33226. if (!boundingInfo) {
  33227. return false;
  33228. }
  33229. return ray.intersectsBox(boundingInfo.boundingBox);
  33230. };
  33231. /**
  33232. * Returns an object IntersectionInfo.
  33233. */
  33234. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33235. var intersectInfo = null;
  33236. var material = this.getMaterial();
  33237. if (!material) {
  33238. return null;
  33239. }
  33240. switch (material.fillMode) {
  33241. case BABYLON.Material.PointListDrawMode:
  33242. case BABYLON.Material.LineListDrawMode:
  33243. case BABYLON.Material.LineLoopDrawMode:
  33244. case BABYLON.Material.LineStripDrawMode:
  33245. case BABYLON.Material.TriangleFanDrawMode:
  33246. case BABYLON.Material.TriangleStripDrawMode:
  33247. return null;
  33248. }
  33249. // LineMesh first as it's also a Mesh...
  33250. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33251. var lineMesh = this._mesh;
  33252. // Line test
  33253. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33254. var p0 = positions[indices[index]];
  33255. var p1 = positions[indices[index + 1]];
  33256. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33257. if (length < 0) {
  33258. continue;
  33259. }
  33260. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33261. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33262. if (fastCheck) {
  33263. break;
  33264. }
  33265. }
  33266. }
  33267. }
  33268. else {
  33269. // Triangles test
  33270. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33271. var p0 = positions[indices[index]];
  33272. var p1 = positions[indices[index + 1]];
  33273. var p2 = positions[indices[index + 2]];
  33274. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33275. if (currentIntersectInfo) {
  33276. if (currentIntersectInfo.distance < 0) {
  33277. continue;
  33278. }
  33279. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33280. intersectInfo = currentIntersectInfo;
  33281. intersectInfo.faceId = index / 3;
  33282. if (fastCheck) {
  33283. break;
  33284. }
  33285. }
  33286. }
  33287. }
  33288. }
  33289. return intersectInfo;
  33290. };
  33291. SubMesh.prototype._rebuild = function () {
  33292. if (this._linesIndexBuffer) {
  33293. this._linesIndexBuffer = null;
  33294. }
  33295. };
  33296. // Clone
  33297. /**
  33298. * Creates a new Submesh from the passed Mesh.
  33299. */
  33300. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33301. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33302. if (!this.IsGlobal) {
  33303. var boundingInfo = this.getBoundingInfo();
  33304. if (!boundingInfo) {
  33305. return result;
  33306. }
  33307. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33308. }
  33309. return result;
  33310. };
  33311. // Dispose
  33312. /**
  33313. * Disposes the Submesh.
  33314. * Returns nothing.
  33315. */
  33316. SubMesh.prototype.dispose = function () {
  33317. if (this._linesIndexBuffer) {
  33318. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33319. this._linesIndexBuffer = null;
  33320. }
  33321. // Remove from mesh
  33322. var index = this._mesh.subMeshes.indexOf(this);
  33323. this._mesh.subMeshes.splice(index, 1);
  33324. };
  33325. // Statics
  33326. /**
  33327. * Creates a new Submesh from the passed parameters :
  33328. * - materialIndex (integer) : the index of the main mesh material.
  33329. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33330. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33331. * - mesh (Mesh) : the main mesh to create the submesh from.
  33332. * - renderingMesh (optional Mesh) : rendering mesh.
  33333. */
  33334. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33335. var minVertexIndex = Number.MAX_VALUE;
  33336. var maxVertexIndex = -Number.MAX_VALUE;
  33337. renderingMesh = (renderingMesh || mesh);
  33338. var indices = renderingMesh.getIndices();
  33339. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33340. var vertexIndex = indices[index];
  33341. if (vertexIndex < minVertexIndex)
  33342. minVertexIndex = vertexIndex;
  33343. if (vertexIndex > maxVertexIndex)
  33344. maxVertexIndex = vertexIndex;
  33345. }
  33346. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33347. };
  33348. return SubMesh;
  33349. }(BaseSubMesh));
  33350. BABYLON.SubMesh = SubMesh;
  33351. })(BABYLON || (BABYLON = {}));
  33352. //# sourceMappingURL=babylon.subMesh.js.map
  33353. "use strict";
  33354. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33355. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33356. s = arguments[i];
  33357. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33358. t[p] = s[p];
  33359. }
  33360. return t;
  33361. };
  33362. var BABYLON;
  33363. (function (BABYLON) {
  33364. /**
  33365. * Manages the defines for the Material
  33366. */
  33367. var MaterialDefines = /** @class */ (function () {
  33368. function MaterialDefines() {
  33369. this._isDirty = true;
  33370. this._areLightsDirty = true;
  33371. this._areAttributesDirty = true;
  33372. this._areTexturesDirty = true;
  33373. this._areFresnelDirty = true;
  33374. this._areMiscDirty = true;
  33375. this._areImageProcessingDirty = true;
  33376. this._normals = false;
  33377. this._uvs = false;
  33378. this._needNormals = false;
  33379. this._needUVs = false;
  33380. }
  33381. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33382. /**
  33383. * Specifies if the material needs to be re-calculated
  33384. */
  33385. get: function () {
  33386. return this._isDirty;
  33387. },
  33388. enumerable: true,
  33389. configurable: true
  33390. });
  33391. /**
  33392. * Marks the material to indicate that it has been re-calculated
  33393. */
  33394. MaterialDefines.prototype.markAsProcessed = function () {
  33395. this._isDirty = false;
  33396. this._areAttributesDirty = false;
  33397. this._areTexturesDirty = false;
  33398. this._areFresnelDirty = false;
  33399. this._areLightsDirty = false;
  33400. this._areMiscDirty = false;
  33401. this._areImageProcessingDirty = false;
  33402. };
  33403. /**
  33404. * Marks the material to indicate that it needs to be re-calculated
  33405. */
  33406. MaterialDefines.prototype.markAsUnprocessed = function () {
  33407. this._isDirty = true;
  33408. };
  33409. /**
  33410. * Marks the material to indicate all of its defines need to be re-calculated
  33411. */
  33412. MaterialDefines.prototype.markAllAsDirty = function () {
  33413. this._areTexturesDirty = true;
  33414. this._areAttributesDirty = true;
  33415. this._areLightsDirty = true;
  33416. this._areFresnelDirty = true;
  33417. this._areMiscDirty = true;
  33418. this._areImageProcessingDirty = true;
  33419. this._isDirty = true;
  33420. };
  33421. /**
  33422. * Marks the material to indicate that image processing needs to be re-calculated
  33423. */
  33424. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33425. this._areImageProcessingDirty = true;
  33426. this._isDirty = true;
  33427. };
  33428. /**
  33429. * Marks the material to indicate the lights need to be re-calculated
  33430. */
  33431. MaterialDefines.prototype.markAsLightDirty = function () {
  33432. this._areLightsDirty = true;
  33433. this._isDirty = true;
  33434. };
  33435. /**
  33436. * Marks the attribute state as changed
  33437. */
  33438. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33439. this._areAttributesDirty = true;
  33440. this._isDirty = true;
  33441. };
  33442. /**
  33443. * Marks the texture state as changed
  33444. */
  33445. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33446. this._areTexturesDirty = true;
  33447. this._isDirty = true;
  33448. };
  33449. /**
  33450. * Marks the fresnel state as changed
  33451. */
  33452. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33453. this._areFresnelDirty = true;
  33454. this._isDirty = true;
  33455. };
  33456. /**
  33457. * Marks the misc state as changed
  33458. */
  33459. MaterialDefines.prototype.markAsMiscDirty = function () {
  33460. this._areMiscDirty = true;
  33461. this._isDirty = true;
  33462. };
  33463. /**
  33464. * Rebuilds the material defines
  33465. */
  33466. MaterialDefines.prototype.rebuild = function () {
  33467. if (this._keys) {
  33468. delete this._keys;
  33469. }
  33470. this._keys = [];
  33471. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33472. var key = _a[_i];
  33473. if (key[0] === "_") {
  33474. continue;
  33475. }
  33476. this._keys.push(key);
  33477. }
  33478. };
  33479. /**
  33480. * Specifies if two material defines are equal
  33481. * @param other - A material define instance to compare to
  33482. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33483. */
  33484. MaterialDefines.prototype.isEqual = function (other) {
  33485. if (this._keys.length !== other._keys.length) {
  33486. return false;
  33487. }
  33488. for (var index = 0; index < this._keys.length; index++) {
  33489. var prop = this._keys[index];
  33490. if (this[prop] !== other[prop]) {
  33491. return false;
  33492. }
  33493. }
  33494. return true;
  33495. };
  33496. /**
  33497. * Clones this instance's defines to another instance
  33498. * @param other - material defines to clone values to
  33499. */
  33500. MaterialDefines.prototype.cloneTo = function (other) {
  33501. if (this._keys.length !== other._keys.length) {
  33502. other._keys = this._keys.slice(0);
  33503. }
  33504. for (var index = 0; index < this._keys.length; index++) {
  33505. var prop = this._keys[index];
  33506. other[prop] = this[prop];
  33507. }
  33508. };
  33509. /**
  33510. * Resets the material define values
  33511. */
  33512. MaterialDefines.prototype.reset = function () {
  33513. for (var index = 0; index < this._keys.length; index++) {
  33514. var prop = this._keys[index];
  33515. var type = typeof this[prop];
  33516. switch (type) {
  33517. case "number":
  33518. this[prop] = 0;
  33519. break;
  33520. case "string":
  33521. this[prop] = "";
  33522. break;
  33523. default:
  33524. this[prop] = false;
  33525. break;
  33526. }
  33527. }
  33528. };
  33529. /**
  33530. * Converts the material define values to a string
  33531. * @returns - String of material define information
  33532. */
  33533. MaterialDefines.prototype.toString = function () {
  33534. var result = "";
  33535. for (var index = 0; index < this._keys.length; index++) {
  33536. var prop = this._keys[index];
  33537. var value = this[prop];
  33538. var type = typeof value;
  33539. switch (type) {
  33540. case "number":
  33541. case "string":
  33542. result += "#define " + prop + " " + value + "\n";
  33543. break;
  33544. default:
  33545. if (value) {
  33546. result += "#define " + prop + "\n";
  33547. }
  33548. break;
  33549. }
  33550. }
  33551. return result;
  33552. };
  33553. return MaterialDefines;
  33554. }());
  33555. BABYLON.MaterialDefines = MaterialDefines;
  33556. /**
  33557. * Base class for the main features of a material in Babylon.js
  33558. */
  33559. var Material = /** @class */ (function () {
  33560. /**
  33561. * Creates a material instance
  33562. * @param name defines the name of the material
  33563. * @param scene defines the scene to reference
  33564. * @param doNotAdd specifies if the material should be added to the scene
  33565. */
  33566. function Material(name, scene, doNotAdd) {
  33567. /**
  33568. * Specifies if the ready state should be checked on each call
  33569. */
  33570. this.checkReadyOnEveryCall = false;
  33571. /**
  33572. * Specifies if the ready state should be checked once
  33573. */
  33574. this.checkReadyOnlyOnce = false;
  33575. /**
  33576. * The state of the material
  33577. */
  33578. this.state = "";
  33579. /**
  33580. * The alpha value of the material
  33581. */
  33582. this._alpha = 1.0;
  33583. /**
  33584. * Specifies if back face culling is enabled
  33585. */
  33586. this._backFaceCulling = true;
  33587. /**
  33588. * Specifies if the material should be serialized
  33589. */
  33590. this.doNotSerialize = false;
  33591. /**
  33592. * Specifies if the effect should be stored on sub meshes
  33593. */
  33594. this.storeEffectOnSubMeshes = false;
  33595. /**
  33596. * An event triggered when the material is disposed
  33597. */
  33598. this.onDisposeObservable = new BABYLON.Observable();
  33599. /**
  33600. * An event triggered when the material is bound
  33601. */
  33602. this.onBindObservable = new BABYLON.Observable();
  33603. /**
  33604. * An event triggered when the material is unbound
  33605. */
  33606. this.onUnBindObservable = new BABYLON.Observable();
  33607. /**
  33608. * Stores the value of the alpha mode
  33609. */
  33610. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33611. /**
  33612. * Stores the state of the need depth pre-pass value
  33613. */
  33614. this._needDepthPrePass = false;
  33615. /**
  33616. * Specifies if depth writing should be disabled
  33617. */
  33618. this.disableDepthWrite = false;
  33619. /**
  33620. * Specifies if depth writing should be forced
  33621. */
  33622. this.forceDepthWrite = false;
  33623. /**
  33624. * Specifies if there should be a separate pass for culling
  33625. */
  33626. this.separateCullingPass = false;
  33627. /**
  33628. * Stores the state specifing if fog should be enabled
  33629. */
  33630. this._fogEnabled = true;
  33631. /**
  33632. * Stores the size of points
  33633. */
  33634. this.pointSize = 1.0;
  33635. /**
  33636. * Stores the z offset value
  33637. */
  33638. this.zOffset = 0;
  33639. /**
  33640. * Specifies if the material was previously ready
  33641. */
  33642. this._wasPreviouslyReady = false;
  33643. /**
  33644. * Stores the fill mode state
  33645. */
  33646. this._fillMode = Material.TriangleFillMode;
  33647. this.name = name;
  33648. this.id = name || BABYLON.Tools.RandomId();
  33649. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33650. if (this._scene.useRightHandedSystem) {
  33651. this.sideOrientation = Material.ClockWiseSideOrientation;
  33652. }
  33653. else {
  33654. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  33655. }
  33656. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  33657. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  33658. if (!doNotAdd) {
  33659. this._scene.materials.push(this);
  33660. }
  33661. }
  33662. Object.defineProperty(Material, "TriangleFillMode", {
  33663. /**
  33664. * Returns the triangle fill mode
  33665. */
  33666. get: function () {
  33667. return Material._TriangleFillMode;
  33668. },
  33669. enumerable: true,
  33670. configurable: true
  33671. });
  33672. Object.defineProperty(Material, "WireFrameFillMode", {
  33673. /**
  33674. * Returns the wireframe mode
  33675. */
  33676. get: function () {
  33677. return Material._WireFrameFillMode;
  33678. },
  33679. enumerable: true,
  33680. configurable: true
  33681. });
  33682. Object.defineProperty(Material, "PointFillMode", {
  33683. /**
  33684. * Returns the point fill mode
  33685. */
  33686. get: function () {
  33687. return Material._PointFillMode;
  33688. },
  33689. enumerable: true,
  33690. configurable: true
  33691. });
  33692. Object.defineProperty(Material, "PointListDrawMode", {
  33693. /**
  33694. * Returns the point list draw mode
  33695. */
  33696. get: function () {
  33697. return Material._PointListDrawMode;
  33698. },
  33699. enumerable: true,
  33700. configurable: true
  33701. });
  33702. Object.defineProperty(Material, "LineListDrawMode", {
  33703. /**
  33704. * Returns the line list draw mode
  33705. */
  33706. get: function () {
  33707. return Material._LineListDrawMode;
  33708. },
  33709. enumerable: true,
  33710. configurable: true
  33711. });
  33712. Object.defineProperty(Material, "LineLoopDrawMode", {
  33713. /**
  33714. * Returns the line loop draw mode
  33715. */
  33716. get: function () {
  33717. return Material._LineLoopDrawMode;
  33718. },
  33719. enumerable: true,
  33720. configurable: true
  33721. });
  33722. Object.defineProperty(Material, "LineStripDrawMode", {
  33723. /**
  33724. * Returns the line strip draw mode
  33725. */
  33726. get: function () {
  33727. return Material._LineStripDrawMode;
  33728. },
  33729. enumerable: true,
  33730. configurable: true
  33731. });
  33732. Object.defineProperty(Material, "TriangleStripDrawMode", {
  33733. /**
  33734. * Returns the triangle strip draw mode
  33735. */
  33736. get: function () {
  33737. return Material._TriangleStripDrawMode;
  33738. },
  33739. enumerable: true,
  33740. configurable: true
  33741. });
  33742. Object.defineProperty(Material, "TriangleFanDrawMode", {
  33743. /**
  33744. * Returns the triangle fan draw mode
  33745. */
  33746. get: function () {
  33747. return Material._TriangleFanDrawMode;
  33748. },
  33749. enumerable: true,
  33750. configurable: true
  33751. });
  33752. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  33753. /**
  33754. * Returns the clock-wise side orientation
  33755. */
  33756. get: function () {
  33757. return Material._ClockWiseSideOrientation;
  33758. },
  33759. enumerable: true,
  33760. configurable: true
  33761. });
  33762. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  33763. /**
  33764. * Returns the counter clock-wise side orientation
  33765. */
  33766. get: function () {
  33767. return Material._CounterClockWiseSideOrientation;
  33768. },
  33769. enumerable: true,
  33770. configurable: true
  33771. });
  33772. Object.defineProperty(Material, "TextureDirtyFlag", {
  33773. /**
  33774. * Returns the dirty texture flag value
  33775. */
  33776. get: function () {
  33777. return Material._TextureDirtyFlag;
  33778. },
  33779. enumerable: true,
  33780. configurable: true
  33781. });
  33782. Object.defineProperty(Material, "LightDirtyFlag", {
  33783. /**
  33784. * Returns the dirty light flag value
  33785. */
  33786. get: function () {
  33787. return Material._LightDirtyFlag;
  33788. },
  33789. enumerable: true,
  33790. configurable: true
  33791. });
  33792. Object.defineProperty(Material, "FresnelDirtyFlag", {
  33793. /**
  33794. * Returns the dirty fresnel flag value
  33795. */
  33796. get: function () {
  33797. return Material._FresnelDirtyFlag;
  33798. },
  33799. enumerable: true,
  33800. configurable: true
  33801. });
  33802. Object.defineProperty(Material, "AttributesDirtyFlag", {
  33803. /**
  33804. * Returns the dirty attributes flag value
  33805. */
  33806. get: function () {
  33807. return Material._AttributesDirtyFlag;
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. Object.defineProperty(Material, "MiscDirtyFlag", {
  33813. /**
  33814. * Returns the dirty misc flag value
  33815. */
  33816. get: function () {
  33817. return Material._MiscDirtyFlag;
  33818. },
  33819. enumerable: true,
  33820. configurable: true
  33821. });
  33822. Object.defineProperty(Material.prototype, "alpha", {
  33823. /**
  33824. * Gets the alpha value of the material
  33825. */
  33826. get: function () {
  33827. return this._alpha;
  33828. },
  33829. /**
  33830. * Sets the alpha value of the material
  33831. */
  33832. set: function (value) {
  33833. if (this._alpha === value) {
  33834. return;
  33835. }
  33836. this._alpha = value;
  33837. this.markAsDirty(Material.MiscDirtyFlag);
  33838. },
  33839. enumerable: true,
  33840. configurable: true
  33841. });
  33842. Object.defineProperty(Material.prototype, "backFaceCulling", {
  33843. /**
  33844. * Gets the back-face culling state
  33845. */
  33846. get: function () {
  33847. return this._backFaceCulling;
  33848. },
  33849. /**
  33850. * Sets the back-face culling state
  33851. */
  33852. set: function (value) {
  33853. if (this._backFaceCulling === value) {
  33854. return;
  33855. }
  33856. this._backFaceCulling = value;
  33857. this.markAsDirty(Material.TextureDirtyFlag);
  33858. },
  33859. enumerable: true,
  33860. configurable: true
  33861. });
  33862. Object.defineProperty(Material.prototype, "onDispose", {
  33863. /**
  33864. * Called during a dispose event
  33865. */
  33866. set: function (callback) {
  33867. if (this._onDisposeObserver) {
  33868. this.onDisposeObservable.remove(this._onDisposeObserver);
  33869. }
  33870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33871. },
  33872. enumerable: true,
  33873. configurable: true
  33874. });
  33875. Object.defineProperty(Material.prototype, "onBind", {
  33876. /**
  33877. * Called during a bind event
  33878. */
  33879. set: function (callback) {
  33880. if (this._onBindObserver) {
  33881. this.onBindObservable.remove(this._onBindObserver);
  33882. }
  33883. this._onBindObserver = this.onBindObservable.add(callback);
  33884. },
  33885. enumerable: true,
  33886. configurable: true
  33887. });
  33888. Object.defineProperty(Material.prototype, "alphaMode", {
  33889. /**
  33890. * Gets the value of the alpha mode
  33891. */
  33892. get: function () {
  33893. return this._alphaMode;
  33894. },
  33895. /**
  33896. * Sets the value of the alpha mode.
  33897. *
  33898. * | Value | Type | Description |
  33899. * | --- | --- | --- |
  33900. * | 0 | ALPHA_DISABLE | |
  33901. * | 1 | ALPHA_ADD | |
  33902. * | 2 | ALPHA_COMBINE | |
  33903. * | 3 | ALPHA_SUBTRACT | |
  33904. * | 4 | ALPHA_MULTIPLY | |
  33905. * | 5 | ALPHA_MAXIMIZED | |
  33906. * | 6 | ALPHA_ONEONE | |
  33907. * | 7 | ALPHA_PREMULTIPLIED | |
  33908. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  33909. * | 9 | ALPHA_INTERPOLATE | |
  33910. * | 10 | ALPHA_SCREENMODE | |
  33911. *
  33912. */
  33913. set: function (value) {
  33914. if (this._alphaMode === value) {
  33915. return;
  33916. }
  33917. this._alphaMode = value;
  33918. this.markAsDirty(Material.TextureDirtyFlag);
  33919. },
  33920. enumerable: true,
  33921. configurable: true
  33922. });
  33923. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  33924. /**
  33925. * Gets the depth pre-pass value
  33926. */
  33927. get: function () {
  33928. return this._needDepthPrePass;
  33929. },
  33930. /**
  33931. * Sets the need depth pre-pass value
  33932. */
  33933. set: function (value) {
  33934. if (this._needDepthPrePass === value) {
  33935. return;
  33936. }
  33937. this._needDepthPrePass = value;
  33938. if (this._needDepthPrePass) {
  33939. this.checkReadyOnEveryCall = true;
  33940. }
  33941. },
  33942. enumerable: true,
  33943. configurable: true
  33944. });
  33945. Object.defineProperty(Material.prototype, "fogEnabled", {
  33946. /**
  33947. * Gets the value of the fog enabled state
  33948. */
  33949. get: function () {
  33950. return this._fogEnabled;
  33951. },
  33952. /**
  33953. * Sets the state for enabling fog
  33954. */
  33955. set: function (value) {
  33956. if (this._fogEnabled === value) {
  33957. return;
  33958. }
  33959. this._fogEnabled = value;
  33960. this.markAsDirty(Material.MiscDirtyFlag);
  33961. },
  33962. enumerable: true,
  33963. configurable: true
  33964. });
  33965. Object.defineProperty(Material.prototype, "wireframe", {
  33966. /**
  33967. * Gets a value specifying if wireframe mode is enabled
  33968. */
  33969. get: function () {
  33970. switch (this._fillMode) {
  33971. case Material.WireFrameFillMode:
  33972. case Material.LineListDrawMode:
  33973. case Material.LineLoopDrawMode:
  33974. case Material.LineStripDrawMode:
  33975. return true;
  33976. }
  33977. return this._scene.forceWireframe;
  33978. },
  33979. /**
  33980. * Sets the state of wireframe mode
  33981. */
  33982. set: function (value) {
  33983. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  33984. },
  33985. enumerable: true,
  33986. configurable: true
  33987. });
  33988. Object.defineProperty(Material.prototype, "pointsCloud", {
  33989. /**
  33990. * Gets the value specifying if point clouds are enabled
  33991. */
  33992. get: function () {
  33993. switch (this._fillMode) {
  33994. case Material.PointFillMode:
  33995. case Material.PointListDrawMode:
  33996. return true;
  33997. }
  33998. return this._scene.forcePointsCloud;
  33999. },
  34000. /**
  34001. * Sets the state of point cloud mode
  34002. */
  34003. set: function (value) {
  34004. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34005. },
  34006. enumerable: true,
  34007. configurable: true
  34008. });
  34009. Object.defineProperty(Material.prototype, "fillMode", {
  34010. /**
  34011. * Gets the material fill mode
  34012. */
  34013. get: function () {
  34014. return this._fillMode;
  34015. },
  34016. /**
  34017. * Sets the material fill mode
  34018. */
  34019. set: function (value) {
  34020. if (this._fillMode === value) {
  34021. return;
  34022. }
  34023. this._fillMode = value;
  34024. this.markAsDirty(Material.MiscDirtyFlag);
  34025. },
  34026. enumerable: true,
  34027. configurable: true
  34028. });
  34029. /**
  34030. * Returns a string representation of the current material
  34031. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34032. * @returns a string with material information
  34033. */
  34034. Material.prototype.toString = function (fullDetails) {
  34035. var ret = "Name: " + this.name;
  34036. if (fullDetails) {
  34037. }
  34038. return ret;
  34039. };
  34040. /**
  34041. * Gets the class name of the material
  34042. * @returns a string with the class name of the material
  34043. */
  34044. Material.prototype.getClassName = function () {
  34045. return "Material";
  34046. };
  34047. Object.defineProperty(Material.prototype, "isFrozen", {
  34048. /**
  34049. * Specifies if updates for the material been locked
  34050. */
  34051. get: function () {
  34052. return this.checkReadyOnlyOnce;
  34053. },
  34054. enumerable: true,
  34055. configurable: true
  34056. });
  34057. /**
  34058. * Locks updates for the material
  34059. */
  34060. Material.prototype.freeze = function () {
  34061. this.checkReadyOnlyOnce = true;
  34062. };
  34063. /**
  34064. * Unlocks updates for the material
  34065. */
  34066. Material.prototype.unfreeze = function () {
  34067. this.checkReadyOnlyOnce = false;
  34068. };
  34069. /**
  34070. * Specifies if the material is ready to be used
  34071. * @param mesh defines the mesh to check
  34072. * @param useInstances specifies if instances should be used
  34073. * @returns a boolean indicating if the material is ready to be used
  34074. */
  34075. Material.prototype.isReady = function (mesh, useInstances) {
  34076. return true;
  34077. };
  34078. /**
  34079. * Specifies that the submesh is ready to be used
  34080. * @param mesh defines the mesh to check
  34081. * @param subMesh defines which submesh to check
  34082. * @param useInstances specifies that instances should be used
  34083. * @returns a boolean indicating that the submesh is ready or not
  34084. */
  34085. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34086. return false;
  34087. };
  34088. /**
  34089. * Returns the material effect
  34090. * @returns the effect associated with the material
  34091. */
  34092. Material.prototype.getEffect = function () {
  34093. return this._effect;
  34094. };
  34095. /**
  34096. * Returns the current scene
  34097. * @returns a Scene
  34098. */
  34099. Material.prototype.getScene = function () {
  34100. return this._scene;
  34101. };
  34102. /**
  34103. * Specifies if the material will require alpha blending
  34104. * @returns a boolean specifying if alpha blending is needed
  34105. */
  34106. Material.prototype.needAlphaBlending = function () {
  34107. return (this.alpha < 1.0);
  34108. };
  34109. /**
  34110. * Specifies if the mesh will require alpha blending
  34111. * @param mesh defines the mesh to check
  34112. * @returns a boolean specifying if alpha blending is needed for the mesh
  34113. */
  34114. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34115. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34116. };
  34117. /**
  34118. * Specifies if this material should be rendered in alpha test mode
  34119. * @returns a boolean specifying if an alpha test is needed.
  34120. */
  34121. Material.prototype.needAlphaTesting = function () {
  34122. return false;
  34123. };
  34124. /**
  34125. * Gets the texture used for the alpha test
  34126. * @returns the texture to use for alpha testing
  34127. */
  34128. Material.prototype.getAlphaTestTexture = function () {
  34129. return null;
  34130. };
  34131. /**
  34132. * Marks the material to indicate that it needs to be re-calculated
  34133. */
  34134. Material.prototype.markDirty = function () {
  34135. this._wasPreviouslyReady = false;
  34136. };
  34137. /** @ignore */
  34138. Material.prototype._preBind = function (effect, overrideOrientation) {
  34139. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34140. var engine = this._scene.getEngine();
  34141. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34142. var reverse = orientation === Material.ClockWiseSideOrientation;
  34143. engine.enableEffect(effect ? effect : this._effect);
  34144. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34145. return reverse;
  34146. };
  34147. /**
  34148. * Binds the material to the mesh
  34149. * @param world defines the world transformation matrix
  34150. * @param mesh defines the mesh to bind the material to
  34151. */
  34152. Material.prototype.bind = function (world, mesh) {
  34153. };
  34154. /**
  34155. * Binds the submesh to the material
  34156. * @param world defines the world transformation matrix
  34157. * @param mesh defines the mesh containing the submesh
  34158. * @param subMesh defines the submesh to bind the material to
  34159. */
  34160. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34161. };
  34162. /**
  34163. * Binds the world matrix to the material
  34164. * @param world defines the world transformation matrix
  34165. */
  34166. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34167. };
  34168. /**
  34169. * Binds the scene's uniform buffer to the effect.
  34170. * @param effect defines the effect to bind to the scene uniform buffer
  34171. * @param sceneUbo defines the uniform buffer storing scene data
  34172. */
  34173. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34174. sceneUbo.bindToEffect(effect, "Scene");
  34175. };
  34176. /**
  34177. * Binds the view matrix to the effect
  34178. * @param effect defines the effect to bind the view matrix to
  34179. */
  34180. Material.prototype.bindView = function (effect) {
  34181. if (!this._useUBO) {
  34182. effect.setMatrix("view", this.getScene().getViewMatrix());
  34183. }
  34184. else {
  34185. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34186. }
  34187. };
  34188. /**
  34189. * Binds the view projection matrix to the effect
  34190. * @param effect defines the effect to bind the view projection matrix to
  34191. */
  34192. Material.prototype.bindViewProjection = function (effect) {
  34193. if (!this._useUBO) {
  34194. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34195. }
  34196. else {
  34197. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34198. }
  34199. };
  34200. /**
  34201. * Specifies if material alpha testing should be turned on for the mesh
  34202. * @param mesh defines the mesh to check
  34203. */
  34204. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34205. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34206. };
  34207. /**
  34208. * Processes to execute after binding the material to a mesh
  34209. * @param mesh defines the rendered mesh
  34210. */
  34211. Material.prototype._afterBind = function (mesh) {
  34212. this._scene._cachedMaterial = this;
  34213. if (mesh) {
  34214. this._scene._cachedVisibility = mesh.visibility;
  34215. }
  34216. else {
  34217. this._scene._cachedVisibility = 1;
  34218. }
  34219. if (mesh) {
  34220. this.onBindObservable.notifyObservers(mesh);
  34221. }
  34222. if (this.disableDepthWrite) {
  34223. var engine = this._scene.getEngine();
  34224. this._cachedDepthWriteState = engine.getDepthWrite();
  34225. engine.setDepthWrite(false);
  34226. }
  34227. };
  34228. /**
  34229. * Unbinds the material from the mesh
  34230. */
  34231. Material.prototype.unbind = function () {
  34232. this.onUnBindObservable.notifyObservers(this);
  34233. if (this.disableDepthWrite) {
  34234. var engine = this._scene.getEngine();
  34235. engine.setDepthWrite(this._cachedDepthWriteState);
  34236. }
  34237. };
  34238. /**
  34239. * Gets the active textures from the material
  34240. * @returns an array of textures
  34241. */
  34242. Material.prototype.getActiveTextures = function () {
  34243. return [];
  34244. };
  34245. /**
  34246. * Specifies if the material uses a texture
  34247. * @param texture defines the texture to check against the material
  34248. * @returns a boolean specifying if the material uses the texture
  34249. */
  34250. Material.prototype.hasTexture = function (texture) {
  34251. return false;
  34252. };
  34253. /**
  34254. * Makes a duplicate of the material, and gives it a new name
  34255. * @param name defines the new name for the duplicated material
  34256. * @returns the cloned material
  34257. */
  34258. Material.prototype.clone = function (name) {
  34259. return null;
  34260. };
  34261. /**
  34262. * Gets the meshes bound to the material
  34263. * @returns an array of meshes bound to the material
  34264. */
  34265. Material.prototype.getBindedMeshes = function () {
  34266. var result = new Array();
  34267. for (var index = 0; index < this._scene.meshes.length; index++) {
  34268. var mesh = this._scene.meshes[index];
  34269. if (mesh.material === this) {
  34270. result.push(mesh);
  34271. }
  34272. }
  34273. return result;
  34274. };
  34275. /**
  34276. * Force shader compilation
  34277. * @param mesh defines the mesh associated with this material
  34278. * @param onCompiled defines a function to execute once the material is compiled
  34279. * @param options defines the options to configure the compilation
  34280. */
  34281. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34282. var _this = this;
  34283. var localOptions = __assign({ clipPlane: false }, options);
  34284. var subMesh = new BABYLON.BaseSubMesh();
  34285. var scene = this.getScene();
  34286. var checkReady = function () {
  34287. if (!_this._scene || !_this._scene.getEngine()) {
  34288. return;
  34289. }
  34290. if (subMesh._materialDefines) {
  34291. subMesh._materialDefines._renderId = -1;
  34292. }
  34293. var clipPlaneState = scene.clipPlane;
  34294. if (localOptions.clipPlane) {
  34295. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34296. }
  34297. if (_this.storeEffectOnSubMeshes) {
  34298. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34299. if (onCompiled) {
  34300. onCompiled(_this);
  34301. }
  34302. }
  34303. else {
  34304. setTimeout(checkReady, 16);
  34305. }
  34306. }
  34307. else {
  34308. if (_this.isReady(mesh)) {
  34309. if (onCompiled) {
  34310. onCompiled(_this);
  34311. }
  34312. }
  34313. else {
  34314. setTimeout(checkReady, 16);
  34315. }
  34316. }
  34317. if (localOptions.clipPlane) {
  34318. scene.clipPlane = clipPlaneState;
  34319. }
  34320. };
  34321. checkReady();
  34322. };
  34323. /**
  34324. * Force shader compilation
  34325. * @param mesh defines the mesh that will use this material
  34326. * @param options defines additional options for compiling the shaders
  34327. * @returns a promise that resolves when the compilation completes
  34328. */
  34329. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34330. var _this = this;
  34331. return new Promise(function (resolve) {
  34332. _this.forceCompilation(mesh, function () {
  34333. resolve();
  34334. }, options);
  34335. });
  34336. };
  34337. /**
  34338. * Marks a define in the material to indicate that it needs to be re-computed
  34339. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34340. */
  34341. Material.prototype.markAsDirty = function (flag) {
  34342. if (flag & Material.TextureDirtyFlag) {
  34343. this._markAllSubMeshesAsTexturesDirty();
  34344. }
  34345. if (flag & Material.LightDirtyFlag) {
  34346. this._markAllSubMeshesAsLightsDirty();
  34347. }
  34348. if (flag & Material.FresnelDirtyFlag) {
  34349. this._markAllSubMeshesAsFresnelDirty();
  34350. }
  34351. if (flag & Material.AttributesDirtyFlag) {
  34352. this._markAllSubMeshesAsAttributesDirty();
  34353. }
  34354. if (flag & Material.MiscDirtyFlag) {
  34355. this._markAllSubMeshesAsMiscDirty();
  34356. }
  34357. this.getScene().resetCachedMaterial();
  34358. };
  34359. /**
  34360. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34361. * @param func defines a function which checks material defines against the submeshes
  34362. */
  34363. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34364. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34365. var mesh = _a[_i];
  34366. if (!mesh.subMeshes) {
  34367. continue;
  34368. }
  34369. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34370. var subMesh = _c[_b];
  34371. if (subMesh.getMaterial() !== this) {
  34372. continue;
  34373. }
  34374. if (!subMesh._materialDefines) {
  34375. continue;
  34376. }
  34377. func(subMesh._materialDefines);
  34378. }
  34379. }
  34380. };
  34381. /**
  34382. * Indicates that image processing needs to be re-calculated for all submeshes
  34383. */
  34384. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34385. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34386. };
  34387. /**
  34388. * Indicates that textures need to be re-calculated for all submeshes
  34389. */
  34390. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34391. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34392. };
  34393. /**
  34394. * Indicates that fresnel needs to be re-calculated for all submeshes
  34395. */
  34396. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34397. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34398. };
  34399. /**
  34400. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34401. */
  34402. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34403. this._markAllSubMeshesAsDirty(function (defines) {
  34404. defines.markAsFresnelDirty();
  34405. defines.markAsMiscDirty();
  34406. });
  34407. };
  34408. /**
  34409. * Indicates that lights need to be re-calculated for all submeshes
  34410. */
  34411. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34412. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34413. };
  34414. /**
  34415. * Indicates that attributes need to be re-calculated for all submeshes
  34416. */
  34417. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34418. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34419. };
  34420. /**
  34421. * Indicates that misc needs to be re-calculated for all submeshes
  34422. */
  34423. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34424. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34425. };
  34426. /**
  34427. * Indicates that textures and misc need to be re-calculated for all submeshes
  34428. */
  34429. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34430. this._markAllSubMeshesAsDirty(function (defines) {
  34431. defines.markAsTexturesDirty();
  34432. defines.markAsMiscDirty();
  34433. });
  34434. };
  34435. /**
  34436. * Disposes the material
  34437. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34438. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34439. */
  34440. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34441. // Animations
  34442. this.getScene().stopAnimation(this);
  34443. this.getScene().freeProcessedMaterials();
  34444. // Remove from scene
  34445. var index = this._scene.materials.indexOf(this);
  34446. if (index >= 0) {
  34447. this._scene.materials.splice(index, 1);
  34448. }
  34449. // Remove from meshes
  34450. for (index = 0; index < this._scene.meshes.length; index++) {
  34451. var mesh = this._scene.meshes[index];
  34452. if (mesh.material === this) {
  34453. mesh.material = null;
  34454. if (mesh.geometry) {
  34455. var geometry = (mesh.geometry);
  34456. if (this.storeEffectOnSubMeshes) {
  34457. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34458. var subMesh = _a[_i];
  34459. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34460. if (forceDisposeEffect && subMesh._materialEffect) {
  34461. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34462. }
  34463. }
  34464. }
  34465. else {
  34466. geometry._releaseVertexArrayObject(this._effect);
  34467. }
  34468. }
  34469. }
  34470. }
  34471. this._uniformBuffer.dispose();
  34472. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34473. if (forceDisposeEffect && this._effect) {
  34474. if (!this.storeEffectOnSubMeshes) {
  34475. this._scene.getEngine()._releaseEffect(this._effect);
  34476. }
  34477. this._effect = null;
  34478. }
  34479. // Callback
  34480. this.onDisposeObservable.notifyObservers(this);
  34481. this.onDisposeObservable.clear();
  34482. this.onBindObservable.clear();
  34483. this.onUnBindObservable.clear();
  34484. };
  34485. /**
  34486. * Serializes this material
  34487. * @returns the serialized material object
  34488. */
  34489. Material.prototype.serialize = function () {
  34490. return BABYLON.SerializationHelper.Serialize(this);
  34491. };
  34492. /**
  34493. * Creates a MultiMaterial from parsed MultiMaterial data.
  34494. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34495. * @param scene defines the hosting scene
  34496. * @returns a new MultiMaterial
  34497. */
  34498. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34499. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34500. multiMaterial.id = parsedMultiMaterial.id;
  34501. if (BABYLON.Tags) {
  34502. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34503. }
  34504. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34505. var subMatId = parsedMultiMaterial.materials[matIndex];
  34506. if (subMatId) {
  34507. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34508. }
  34509. else {
  34510. multiMaterial.subMaterials.push(null);
  34511. }
  34512. }
  34513. return multiMaterial;
  34514. };
  34515. /**
  34516. * Creates a material from parsed material data
  34517. * @param parsedMaterial defines parsed material data
  34518. * @param scene defines the hosting scene
  34519. * @param rootUrl defines the root URL to use to load textures
  34520. * @returns a new material
  34521. */
  34522. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34523. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34524. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34525. }
  34526. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34527. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34528. if (!BABYLON.LegacyPBRMaterial) {
  34529. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34530. return;
  34531. }
  34532. }
  34533. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34534. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34535. ;
  34536. };
  34537. // Triangle views
  34538. Material._TriangleFillMode = 0;
  34539. Material._WireFrameFillMode = 1;
  34540. Material._PointFillMode = 2;
  34541. // Draw modes
  34542. Material._PointListDrawMode = 3;
  34543. Material._LineListDrawMode = 4;
  34544. Material._LineLoopDrawMode = 5;
  34545. Material._LineStripDrawMode = 6;
  34546. Material._TriangleStripDrawMode = 7;
  34547. Material._TriangleFanDrawMode = 8;
  34548. /**
  34549. * Stores the clock-wise side orientation
  34550. */
  34551. Material._ClockWiseSideOrientation = 0;
  34552. /**
  34553. * Stores the counter clock-wise side orientation
  34554. */
  34555. Material._CounterClockWiseSideOrientation = 1;
  34556. /**
  34557. * The dirty texture flag value
  34558. */
  34559. Material._TextureDirtyFlag = 1;
  34560. /**
  34561. * The dirty light flag value
  34562. */
  34563. Material._LightDirtyFlag = 2;
  34564. /**
  34565. * The dirty fresnel flag value
  34566. */
  34567. Material._FresnelDirtyFlag = 4;
  34568. /**
  34569. * The dirty attribute flag value
  34570. */
  34571. Material._AttributesDirtyFlag = 8;
  34572. /**
  34573. * The dirty misc flag value
  34574. */
  34575. Material._MiscDirtyFlag = 16;
  34576. __decorate([
  34577. BABYLON.serialize()
  34578. ], Material.prototype, "id", void 0);
  34579. __decorate([
  34580. BABYLON.serialize()
  34581. ], Material.prototype, "name", void 0);
  34582. __decorate([
  34583. BABYLON.serialize()
  34584. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34585. __decorate([
  34586. BABYLON.serialize()
  34587. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34588. __decorate([
  34589. BABYLON.serialize()
  34590. ], Material.prototype, "state", void 0);
  34591. __decorate([
  34592. BABYLON.serialize("alpha")
  34593. ], Material.prototype, "_alpha", void 0);
  34594. __decorate([
  34595. BABYLON.serialize("backFaceCulling")
  34596. ], Material.prototype, "_backFaceCulling", void 0);
  34597. __decorate([
  34598. BABYLON.serialize()
  34599. ], Material.prototype, "sideOrientation", void 0);
  34600. __decorate([
  34601. BABYLON.serialize("alphaMode")
  34602. ], Material.prototype, "_alphaMode", void 0);
  34603. __decorate([
  34604. BABYLON.serialize()
  34605. ], Material.prototype, "_needDepthPrePass", void 0);
  34606. __decorate([
  34607. BABYLON.serialize()
  34608. ], Material.prototype, "disableDepthWrite", void 0);
  34609. __decorate([
  34610. BABYLON.serialize()
  34611. ], Material.prototype, "forceDepthWrite", void 0);
  34612. __decorate([
  34613. BABYLON.serialize()
  34614. ], Material.prototype, "separateCullingPass", void 0);
  34615. __decorate([
  34616. BABYLON.serialize("fogEnabled")
  34617. ], Material.prototype, "_fogEnabled", void 0);
  34618. __decorate([
  34619. BABYLON.serialize()
  34620. ], Material.prototype, "pointSize", void 0);
  34621. __decorate([
  34622. BABYLON.serialize()
  34623. ], Material.prototype, "zOffset", void 0);
  34624. __decorate([
  34625. BABYLON.serialize()
  34626. ], Material.prototype, "wireframe", null);
  34627. __decorate([
  34628. BABYLON.serialize()
  34629. ], Material.prototype, "pointsCloud", null);
  34630. __decorate([
  34631. BABYLON.serialize()
  34632. ], Material.prototype, "fillMode", null);
  34633. return Material;
  34634. }());
  34635. BABYLON.Material = Material;
  34636. })(BABYLON || (BABYLON = {}));
  34637. //# sourceMappingURL=babylon.material.js.map
  34638. "use strict";
  34639. var BABYLON;
  34640. (function (BABYLON) {
  34641. var UniformBuffer = /** @class */ (function () {
  34642. /**
  34643. * Uniform buffer objects.
  34644. *
  34645. * Handles blocks of uniform on the GPU.
  34646. *
  34647. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  34648. *
  34649. * For more information, please refer to :
  34650. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  34651. */
  34652. function UniformBuffer(engine, data, dynamic) {
  34653. this._engine = engine;
  34654. this._noUBO = !engine.supportsUniformBuffers;
  34655. this._dynamic = dynamic;
  34656. this._data = data || [];
  34657. this._uniformLocations = {};
  34658. this._uniformSizes = {};
  34659. this._uniformLocationPointer = 0;
  34660. this._needSync = false;
  34661. if (this._noUBO) {
  34662. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  34663. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  34664. this.updateFloat = this._updateFloatForEffect;
  34665. this.updateFloat2 = this._updateFloat2ForEffect;
  34666. this.updateFloat3 = this._updateFloat3ForEffect;
  34667. this.updateFloat4 = this._updateFloat4ForEffect;
  34668. this.updateMatrix = this._updateMatrixForEffect;
  34669. this.updateVector3 = this._updateVector3ForEffect;
  34670. this.updateVector4 = this._updateVector4ForEffect;
  34671. this.updateColor3 = this._updateColor3ForEffect;
  34672. this.updateColor4 = this._updateColor4ForEffect;
  34673. }
  34674. else {
  34675. this._engine._uniformBuffers.push(this);
  34676. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  34677. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  34678. this.updateFloat = this._updateFloatForUniform;
  34679. this.updateFloat2 = this._updateFloat2ForUniform;
  34680. this.updateFloat3 = this._updateFloat3ForUniform;
  34681. this.updateFloat4 = this._updateFloat4ForUniform;
  34682. this.updateMatrix = this._updateMatrixForUniform;
  34683. this.updateVector3 = this._updateVector3ForUniform;
  34684. this.updateVector4 = this._updateVector4ForUniform;
  34685. this.updateColor3 = this._updateColor3ForUniform;
  34686. this.updateColor4 = this._updateColor4ForUniform;
  34687. }
  34688. }
  34689. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  34690. // Properties
  34691. /**
  34692. * Indicates if the buffer is using the WebGL2 UBO implementation,
  34693. * or just falling back on setUniformXXX calls.
  34694. */
  34695. get: function () {
  34696. return !this._noUBO;
  34697. },
  34698. enumerable: true,
  34699. configurable: true
  34700. });
  34701. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  34702. /**
  34703. * Indicates if the WebGL underlying uniform buffer is in sync
  34704. * with the javascript cache data.
  34705. */
  34706. get: function () {
  34707. return !this._needSync;
  34708. },
  34709. enumerable: true,
  34710. configurable: true
  34711. });
  34712. /**
  34713. * Indicates if the WebGL underlying uniform buffer is dynamic.
  34714. * Also, a dynamic UniformBuffer will disable cache verification and always
  34715. * update the underlying WebGL uniform buffer to the GPU.
  34716. */
  34717. UniformBuffer.prototype.isDynamic = function () {
  34718. return this._dynamic !== undefined;
  34719. };
  34720. /**
  34721. * The data cache on JS side.
  34722. */
  34723. UniformBuffer.prototype.getData = function () {
  34724. return this._bufferData;
  34725. };
  34726. /**
  34727. * The underlying WebGL Uniform buffer.
  34728. */
  34729. UniformBuffer.prototype.getBuffer = function () {
  34730. return this._buffer;
  34731. };
  34732. /**
  34733. * std140 layout specifies how to align data within an UBO structure.
  34734. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  34735. * for specs.
  34736. */
  34737. UniformBuffer.prototype._fillAlignment = function (size) {
  34738. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  34739. // and 4x4 matrices
  34740. // TODO : change if other types are used
  34741. var alignment;
  34742. if (size <= 2) {
  34743. alignment = size;
  34744. }
  34745. else {
  34746. alignment = 4;
  34747. }
  34748. if ((this._uniformLocationPointer % alignment) !== 0) {
  34749. var oldPointer = this._uniformLocationPointer;
  34750. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  34751. var diff = this._uniformLocationPointer - oldPointer;
  34752. for (var i = 0; i < diff; i++) {
  34753. this._data.push(0);
  34754. }
  34755. }
  34756. };
  34757. /**
  34758. * Adds an uniform in the buffer.
  34759. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  34760. * for the layout to be correct !
  34761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34762. * @param {number|number[]} size Data size, or data directly.
  34763. */
  34764. UniformBuffer.prototype.addUniform = function (name, size) {
  34765. if (this._noUBO) {
  34766. return;
  34767. }
  34768. if (this._uniformLocations[name] !== undefined) {
  34769. // Already existing uniform
  34770. return;
  34771. }
  34772. // This function must be called in the order of the shader layout !
  34773. // size can be the size of the uniform, or data directly
  34774. var data;
  34775. if (size instanceof Array) {
  34776. data = size;
  34777. size = data.length;
  34778. }
  34779. else {
  34780. size = size;
  34781. data = [];
  34782. // Fill with zeros
  34783. for (var i = 0; i < size; i++) {
  34784. data.push(0);
  34785. }
  34786. }
  34787. this._fillAlignment(size);
  34788. this._uniformSizes[name] = size;
  34789. this._uniformLocations[name] = this._uniformLocationPointer;
  34790. this._uniformLocationPointer += size;
  34791. for (var i = 0; i < size; i++) {
  34792. this._data.push(data[i]);
  34793. }
  34794. this._needSync = true;
  34795. };
  34796. /**
  34797. * Wrapper for addUniform.
  34798. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34799. * @param {Matrix} mat A 4x4 matrix.
  34800. */
  34801. UniformBuffer.prototype.addMatrix = function (name, mat) {
  34802. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  34803. };
  34804. /**
  34805. * Wrapper for addUniform.
  34806. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34807. * @param {number} x
  34808. * @param {number} y
  34809. */
  34810. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  34811. var temp = [x, y];
  34812. this.addUniform(name, temp);
  34813. };
  34814. /**
  34815. * Wrapper for addUniform.
  34816. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34817. * @param {number} x
  34818. * @param {number} y
  34819. * @param {number} z
  34820. */
  34821. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  34822. var temp = [x, y, z];
  34823. this.addUniform(name, temp);
  34824. };
  34825. /**
  34826. * Wrapper for addUniform.
  34827. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34828. * @param {Color3} color
  34829. */
  34830. UniformBuffer.prototype.addColor3 = function (name, color) {
  34831. var temp = new Array();
  34832. color.toArray(temp);
  34833. this.addUniform(name, temp);
  34834. };
  34835. /**
  34836. * Wrapper for addUniform.
  34837. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34838. * @param {Color3} color
  34839. * @param {number} alpha
  34840. */
  34841. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  34842. var temp = new Array();
  34843. color.toArray(temp);
  34844. temp.push(alpha);
  34845. this.addUniform(name, temp);
  34846. };
  34847. /**
  34848. * Wrapper for addUniform.
  34849. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34850. * @param {Vector3} vector
  34851. */
  34852. UniformBuffer.prototype.addVector3 = function (name, vector) {
  34853. var temp = new Array();
  34854. vector.toArray(temp);
  34855. this.addUniform(name, temp);
  34856. };
  34857. /**
  34858. * Wrapper for addUniform.
  34859. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34860. */
  34861. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  34862. this.addUniform(name, 12);
  34863. };
  34864. /**
  34865. * Wrapper for addUniform.
  34866. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34867. */
  34868. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  34869. this.addUniform(name, 8);
  34870. };
  34871. /**
  34872. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  34873. */
  34874. UniformBuffer.prototype.create = function () {
  34875. if (this._noUBO) {
  34876. return;
  34877. }
  34878. if (this._buffer) {
  34879. return; // nothing to do
  34880. }
  34881. // See spec, alignment must be filled as a vec4
  34882. this._fillAlignment(4);
  34883. this._bufferData = new Float32Array(this._data);
  34884. this._rebuild();
  34885. this._needSync = true;
  34886. };
  34887. UniformBuffer.prototype._rebuild = function () {
  34888. if (this._noUBO) {
  34889. return;
  34890. }
  34891. if (this._dynamic) {
  34892. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  34893. }
  34894. else {
  34895. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  34896. }
  34897. };
  34898. /**
  34899. * Updates the WebGL Uniform Buffer on the GPU.
  34900. * If the `dynamic` flag is set to true, no cache comparison is done.
  34901. * Otherwise, the buffer will be updated only if the cache differs.
  34902. */
  34903. UniformBuffer.prototype.update = function () {
  34904. if (!this._buffer) {
  34905. this.create();
  34906. return;
  34907. }
  34908. if (!this._dynamic && !this._needSync) {
  34909. return;
  34910. }
  34911. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  34912. this._needSync = false;
  34913. };
  34914. /**
  34915. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  34916. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  34917. * @param {number[]|Float32Array} data Flattened data
  34918. * @param {number} size Size of the data.
  34919. */
  34920. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  34921. var location = this._uniformLocations[uniformName];
  34922. if (location === undefined) {
  34923. if (this._buffer) {
  34924. // Cannot add an uniform if the buffer is already created
  34925. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  34926. return;
  34927. }
  34928. this.addUniform(uniformName, size);
  34929. location = this._uniformLocations[uniformName];
  34930. }
  34931. if (!this._buffer) {
  34932. this.create();
  34933. }
  34934. if (!this._dynamic) {
  34935. // Cache for static uniform buffers
  34936. var changed = false;
  34937. for (var i = 0; i < size; i++) {
  34938. if (this._bufferData[location + i] !== data[i]) {
  34939. changed = true;
  34940. this._bufferData[location + i] = data[i];
  34941. }
  34942. }
  34943. this._needSync = this._needSync || changed;
  34944. }
  34945. else {
  34946. // No cache for dynamic
  34947. for (var i = 0; i < size; i++) {
  34948. this._bufferData[location + i] = data[i];
  34949. }
  34950. }
  34951. };
  34952. // Update methods
  34953. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  34954. // To match std140, matrix must be realigned
  34955. for (var i = 0; i < 3; i++) {
  34956. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  34957. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  34958. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  34959. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  34960. }
  34961. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  34962. };
  34963. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  34964. this._currentEffect.setMatrix3x3(name, matrix);
  34965. };
  34966. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  34967. this._currentEffect.setMatrix2x2(name, matrix);
  34968. };
  34969. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  34970. // To match std140, matrix must be realigned
  34971. for (var i = 0; i < 2; i++) {
  34972. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  34973. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  34974. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  34975. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  34976. }
  34977. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  34978. };
  34979. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  34980. this._currentEffect.setFloat(name, x);
  34981. };
  34982. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  34983. UniformBuffer._tempBuffer[0] = x;
  34984. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  34985. };
  34986. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  34987. if (suffix === void 0) { suffix = ""; }
  34988. this._currentEffect.setFloat2(name + suffix, x, y);
  34989. };
  34990. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  34991. if (suffix === void 0) { suffix = ""; }
  34992. UniformBuffer._tempBuffer[0] = x;
  34993. UniformBuffer._tempBuffer[1] = y;
  34994. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  34995. };
  34996. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  34997. if (suffix === void 0) { suffix = ""; }
  34998. this._currentEffect.setFloat3(name + suffix, x, y, z);
  34999. };
  35000. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35001. if (suffix === void 0) { suffix = ""; }
  35002. UniformBuffer._tempBuffer[0] = x;
  35003. UniformBuffer._tempBuffer[1] = y;
  35004. UniformBuffer._tempBuffer[2] = z;
  35005. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35006. };
  35007. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35008. if (suffix === void 0) { suffix = ""; }
  35009. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35010. };
  35011. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35012. if (suffix === void 0) { suffix = ""; }
  35013. UniformBuffer._tempBuffer[0] = x;
  35014. UniformBuffer._tempBuffer[1] = y;
  35015. UniformBuffer._tempBuffer[2] = z;
  35016. UniformBuffer._tempBuffer[3] = w;
  35017. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35018. };
  35019. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35020. this._currentEffect.setMatrix(name, mat);
  35021. };
  35022. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35023. this.updateUniform(name, mat.toArray(), 16);
  35024. };
  35025. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35026. this._currentEffect.setVector3(name, vector);
  35027. };
  35028. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35029. vector.toArray(UniformBuffer._tempBuffer);
  35030. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35031. };
  35032. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35033. this._currentEffect.setVector4(name, vector);
  35034. };
  35035. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35036. vector.toArray(UniformBuffer._tempBuffer);
  35037. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35038. };
  35039. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35040. if (suffix === void 0) { suffix = ""; }
  35041. this._currentEffect.setColor3(name + suffix, color);
  35042. };
  35043. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35044. if (suffix === void 0) { suffix = ""; }
  35045. color.toArray(UniformBuffer._tempBuffer);
  35046. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35047. };
  35048. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35049. if (suffix === void 0) { suffix = ""; }
  35050. this._currentEffect.setColor4(name + suffix, color, alpha);
  35051. };
  35052. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35053. if (suffix === void 0) { suffix = ""; }
  35054. color.toArray(UniformBuffer._tempBuffer);
  35055. UniformBuffer._tempBuffer[3] = alpha;
  35056. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35057. };
  35058. /**
  35059. * Sets a sampler uniform on the effect.
  35060. * @param {string} name Name of the sampler.
  35061. * @param {Texture} texture
  35062. */
  35063. UniformBuffer.prototype.setTexture = function (name, texture) {
  35064. this._currentEffect.setTexture(name, texture);
  35065. };
  35066. /**
  35067. * Directly updates the value of the uniform in the cache AND on the GPU.
  35068. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35069. * @param {number[]|Float32Array} data Flattened data
  35070. */
  35071. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35072. this.updateUniform(uniformName, data, data.length);
  35073. this.update();
  35074. };
  35075. /**
  35076. * Binds this uniform buffer to an effect.
  35077. * @param {Effect} effect
  35078. * @param {string} name Name of the uniform block in the shader.
  35079. */
  35080. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35081. this._currentEffect = effect;
  35082. if (this._noUBO || !this._buffer) {
  35083. return;
  35084. }
  35085. effect.bindUniformBuffer(this._buffer, name);
  35086. };
  35087. /**
  35088. * Disposes the uniform buffer.
  35089. */
  35090. UniformBuffer.prototype.dispose = function () {
  35091. if (this._noUBO) {
  35092. return;
  35093. }
  35094. var index = this._engine._uniformBuffers.indexOf(this);
  35095. if (index !== -1) {
  35096. this._engine._uniformBuffers.splice(index, 1);
  35097. }
  35098. if (!this._buffer) {
  35099. return;
  35100. }
  35101. if (this._engine._releaseBuffer(this._buffer)) {
  35102. this._buffer = null;
  35103. }
  35104. };
  35105. // Pool for avoiding memory leaks
  35106. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35107. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35108. return UniformBuffer;
  35109. }());
  35110. BABYLON.UniformBuffer = UniformBuffer;
  35111. })(BABYLON || (BABYLON = {}));
  35112. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35113. "use strict";
  35114. var BABYLON;
  35115. (function (BABYLON) {
  35116. var VertexData = /** @class */ (function () {
  35117. function VertexData() {
  35118. }
  35119. VertexData.prototype.set = function (data, kind) {
  35120. switch (kind) {
  35121. case BABYLON.VertexBuffer.PositionKind:
  35122. this.positions = data;
  35123. break;
  35124. case BABYLON.VertexBuffer.NormalKind:
  35125. this.normals = data;
  35126. break;
  35127. case BABYLON.VertexBuffer.TangentKind:
  35128. this.tangents = data;
  35129. break;
  35130. case BABYLON.VertexBuffer.UVKind:
  35131. this.uvs = data;
  35132. break;
  35133. case BABYLON.VertexBuffer.UV2Kind:
  35134. this.uvs2 = data;
  35135. break;
  35136. case BABYLON.VertexBuffer.UV3Kind:
  35137. this.uvs3 = data;
  35138. break;
  35139. case BABYLON.VertexBuffer.UV4Kind:
  35140. this.uvs4 = data;
  35141. break;
  35142. case BABYLON.VertexBuffer.UV5Kind:
  35143. this.uvs5 = data;
  35144. break;
  35145. case BABYLON.VertexBuffer.UV6Kind:
  35146. this.uvs6 = data;
  35147. break;
  35148. case BABYLON.VertexBuffer.ColorKind:
  35149. this.colors = data;
  35150. break;
  35151. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35152. this.matricesIndices = data;
  35153. break;
  35154. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35155. this.matricesWeights = data;
  35156. break;
  35157. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35158. this.matricesIndicesExtra = data;
  35159. break;
  35160. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35161. this.matricesWeightsExtra = data;
  35162. break;
  35163. }
  35164. };
  35165. /**
  35166. * Associates the vertexData to the passed Mesh.
  35167. * Sets it as updatable or not (default `false`).
  35168. * Returns the VertexData.
  35169. */
  35170. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35171. this._applyTo(mesh, updatable);
  35172. return this;
  35173. };
  35174. /**
  35175. * Associates the vertexData to the passed Geometry.
  35176. * Sets it as updatable or not (default `false`).
  35177. * Returns the VertexData.
  35178. */
  35179. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35180. this._applyTo(geometry, updatable);
  35181. return this;
  35182. };
  35183. /**
  35184. * Updates the associated mesh.
  35185. * Returns the VertexData.
  35186. */
  35187. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35188. this._update(mesh);
  35189. return this;
  35190. };
  35191. /**
  35192. * Updates the associated geometry.
  35193. * Returns the VertexData.
  35194. */
  35195. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35196. this._update(geometry);
  35197. return this;
  35198. };
  35199. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35200. if (updatable === void 0) { updatable = false; }
  35201. if (this.positions) {
  35202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35203. }
  35204. if (this.normals) {
  35205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35206. }
  35207. if (this.tangents) {
  35208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35209. }
  35210. if (this.uvs) {
  35211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35212. }
  35213. if (this.uvs2) {
  35214. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35215. }
  35216. if (this.uvs3) {
  35217. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35218. }
  35219. if (this.uvs4) {
  35220. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35221. }
  35222. if (this.uvs5) {
  35223. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35224. }
  35225. if (this.uvs6) {
  35226. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35227. }
  35228. if (this.colors) {
  35229. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35230. }
  35231. if (this.matricesIndices) {
  35232. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35233. }
  35234. if (this.matricesWeights) {
  35235. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35236. }
  35237. if (this.matricesIndicesExtra) {
  35238. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35239. }
  35240. if (this.matricesWeightsExtra) {
  35241. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35242. }
  35243. if (this.indices) {
  35244. meshOrGeometry.setIndices(this.indices, null, updatable);
  35245. }
  35246. return this;
  35247. };
  35248. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35249. if (this.positions) {
  35250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35251. }
  35252. if (this.normals) {
  35253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35254. }
  35255. if (this.tangents) {
  35256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35257. }
  35258. if (this.uvs) {
  35259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35260. }
  35261. if (this.uvs2) {
  35262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35263. }
  35264. if (this.uvs3) {
  35265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35266. }
  35267. if (this.uvs4) {
  35268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35269. }
  35270. if (this.uvs5) {
  35271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35272. }
  35273. if (this.uvs6) {
  35274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35275. }
  35276. if (this.colors) {
  35277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35278. }
  35279. if (this.matricesIndices) {
  35280. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35281. }
  35282. if (this.matricesWeights) {
  35283. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35284. }
  35285. if (this.matricesIndicesExtra) {
  35286. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35287. }
  35288. if (this.matricesWeightsExtra) {
  35289. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35290. }
  35291. if (this.indices) {
  35292. meshOrGeometry.setIndices(this.indices, null);
  35293. }
  35294. return this;
  35295. };
  35296. /**
  35297. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35298. * Returns the VertexData.
  35299. */
  35300. VertexData.prototype.transform = function (matrix) {
  35301. var transformed = BABYLON.Vector3.Zero();
  35302. var index;
  35303. if (this.positions) {
  35304. var position = BABYLON.Vector3.Zero();
  35305. for (index = 0; index < this.positions.length; index += 3) {
  35306. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35307. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35308. this.positions[index] = transformed.x;
  35309. this.positions[index + 1] = transformed.y;
  35310. this.positions[index + 2] = transformed.z;
  35311. }
  35312. }
  35313. if (this.normals) {
  35314. var normal = BABYLON.Vector3.Zero();
  35315. for (index = 0; index < this.normals.length; index += 3) {
  35316. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35317. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35318. this.normals[index] = transformed.x;
  35319. this.normals[index + 1] = transformed.y;
  35320. this.normals[index + 2] = transformed.z;
  35321. }
  35322. }
  35323. if (this.tangents) {
  35324. var tangent = BABYLON.Vector4.Zero();
  35325. var tangentTransformed = BABYLON.Vector4.Zero();
  35326. for (index = 0; index < this.tangents.length; index += 4) {
  35327. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35328. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35329. this.tangents[index] = tangentTransformed.x;
  35330. this.tangents[index + 1] = tangentTransformed.y;
  35331. this.tangents[index + 2] = tangentTransformed.z;
  35332. this.tangents[index + 3] = tangentTransformed.w;
  35333. }
  35334. }
  35335. return this;
  35336. };
  35337. /**
  35338. * Merges the passed VertexData into the current one.
  35339. * Returns the modified VertexData.
  35340. */
  35341. VertexData.prototype.merge = function (other) {
  35342. this._validate();
  35343. other._validate();
  35344. if (!this.normals !== !other.normals ||
  35345. !this.tangents !== !other.tangents ||
  35346. !this.uvs !== !other.uvs ||
  35347. !this.uvs2 !== !other.uvs2 ||
  35348. !this.uvs3 !== !other.uvs3 ||
  35349. !this.uvs4 !== !other.uvs4 ||
  35350. !this.uvs5 !== !other.uvs5 ||
  35351. !this.uvs6 !== !other.uvs6 ||
  35352. !this.colors !== !other.colors ||
  35353. !this.matricesIndices !== !other.matricesIndices ||
  35354. !this.matricesWeights !== !other.matricesWeights ||
  35355. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35356. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35357. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35358. }
  35359. if (other.indices) {
  35360. if (!this.indices) {
  35361. this.indices = [];
  35362. }
  35363. var offset = this.positions ? this.positions.length / 3 : 0;
  35364. for (var index = 0; index < other.indices.length; index++) {
  35365. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35366. this.indices.push(other.indices[index] + offset);
  35367. }
  35368. }
  35369. this.positions = this._mergeElement(this.positions, other.positions);
  35370. this.normals = this._mergeElement(this.normals, other.normals);
  35371. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35372. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35373. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35374. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35375. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35376. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35377. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35378. this.colors = this._mergeElement(this.colors, other.colors);
  35379. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35380. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35381. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35382. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35383. return this;
  35384. };
  35385. VertexData.prototype._mergeElement = function (source, other) {
  35386. if (!source) {
  35387. return other;
  35388. }
  35389. if (!other) {
  35390. return source;
  35391. }
  35392. var len = other.length + source.length;
  35393. var isSrcTypedArray = source instanceof Float32Array;
  35394. var isOthTypedArray = other instanceof Float32Array;
  35395. // use non-loop method when the source is Float32Array
  35396. if (isSrcTypedArray) {
  35397. var ret32 = new Float32Array(len);
  35398. ret32.set(source);
  35399. ret32.set(other, source.length);
  35400. return ret32;
  35401. // source is number[], when other is also use concat
  35402. }
  35403. else if (!isOthTypedArray) {
  35404. return source.concat(other);
  35405. // source is a number[], but other is a Float32Array, loop required
  35406. }
  35407. else {
  35408. var ret = source.slice(0); // copy source to a separate array
  35409. for (var i = 0, len = other.length; i < len; i++) {
  35410. ret.push(other[i]);
  35411. }
  35412. return ret;
  35413. }
  35414. };
  35415. VertexData.prototype._validate = function () {
  35416. if (!this.positions) {
  35417. throw new Error("Positions are required");
  35418. }
  35419. var getElementCount = function (kind, values) {
  35420. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35421. if ((values.length % stride) !== 0) {
  35422. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35423. }
  35424. return values.length / stride;
  35425. };
  35426. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35427. var validateElementCount = function (kind, values) {
  35428. var elementCount = getElementCount(kind, values);
  35429. if (elementCount !== positionsElementCount) {
  35430. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35431. }
  35432. };
  35433. if (this.normals)
  35434. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35435. if (this.tangents)
  35436. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35437. if (this.uvs)
  35438. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35439. if (this.uvs2)
  35440. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35441. if (this.uvs3)
  35442. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35443. if (this.uvs4)
  35444. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35445. if (this.uvs5)
  35446. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35447. if (this.uvs6)
  35448. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35449. if (this.colors)
  35450. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35451. if (this.matricesIndices)
  35452. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35453. if (this.matricesWeights)
  35454. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35455. if (this.matricesIndicesExtra)
  35456. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35457. if (this.matricesWeightsExtra)
  35458. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35459. };
  35460. /**
  35461. * Serializes the VertexData.
  35462. * Returns a serialized object.
  35463. */
  35464. VertexData.prototype.serialize = function () {
  35465. var serializationObject = this.serialize();
  35466. if (this.positions) {
  35467. serializationObject.positions = this.positions;
  35468. }
  35469. if (this.normals) {
  35470. serializationObject.normals = this.normals;
  35471. }
  35472. if (this.tangents) {
  35473. serializationObject.tangents = this.tangents;
  35474. }
  35475. if (this.uvs) {
  35476. serializationObject.uvs = this.uvs;
  35477. }
  35478. if (this.uvs2) {
  35479. serializationObject.uvs2 = this.uvs2;
  35480. }
  35481. if (this.uvs3) {
  35482. serializationObject.uvs3 = this.uvs3;
  35483. }
  35484. if (this.uvs4) {
  35485. serializationObject.uvs4 = this.uvs4;
  35486. }
  35487. if (this.uvs5) {
  35488. serializationObject.uvs5 = this.uvs5;
  35489. }
  35490. if (this.uvs6) {
  35491. serializationObject.uvs6 = this.uvs6;
  35492. }
  35493. if (this.colors) {
  35494. serializationObject.colors = this.colors;
  35495. }
  35496. if (this.matricesIndices) {
  35497. serializationObject.matricesIndices = this.matricesIndices;
  35498. serializationObject.matricesIndices._isExpanded = true;
  35499. }
  35500. if (this.matricesWeights) {
  35501. serializationObject.matricesWeights = this.matricesWeights;
  35502. }
  35503. if (this.matricesIndicesExtra) {
  35504. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35505. serializationObject.matricesIndicesExtra._isExpanded = true;
  35506. }
  35507. if (this.matricesWeightsExtra) {
  35508. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35509. }
  35510. serializationObject.indices = this.indices;
  35511. return serializationObject;
  35512. };
  35513. // Statics
  35514. /**
  35515. * Returns the object VertexData associated to the passed mesh.
  35516. */
  35517. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35518. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35519. };
  35520. /**
  35521. * Returns the object VertexData associated to the passed geometry.
  35522. */
  35523. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35524. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35525. };
  35526. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35527. var result = new VertexData();
  35528. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35529. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35530. }
  35531. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35532. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35533. }
  35534. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35535. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35536. }
  35537. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35538. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35539. }
  35540. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35541. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35542. }
  35543. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35544. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35545. }
  35546. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35547. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35548. }
  35549. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35550. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35551. }
  35552. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35553. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35554. }
  35555. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35556. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35557. }
  35558. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35559. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35560. }
  35561. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35562. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35563. }
  35564. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35565. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35566. }
  35567. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35568. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35569. }
  35570. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35571. return result;
  35572. };
  35573. /**
  35574. * Creates the vertexData of the Ribbon.
  35575. */
  35576. VertexData.CreateRibbon = function (options) {
  35577. var pathArray = options.pathArray;
  35578. var closeArray = options.closeArray || false;
  35579. var closePath = options.closePath || false;
  35580. var invertUV = options.invertUV || false;
  35581. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35582. var offset = options.offset || defaultOffset;
  35583. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35584. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35585. var customUV = options.uvs;
  35586. var customColors = options.colors;
  35587. var positions = [];
  35588. var indices = [];
  35589. var normals = [];
  35590. var uvs = [];
  35591. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35592. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35593. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35594. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35595. var minlg; // minimal length among all paths from pathArray
  35596. var lg = []; // array of path lengths : nb of vertex per path
  35597. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35598. var p; // path iterator
  35599. var i; // point iterator
  35600. var j; // point iterator
  35601. // if single path in pathArray
  35602. if (pathArray.length < 2) {
  35603. var ar1 = [];
  35604. var ar2 = [];
  35605. for (i = 0; i < pathArray[0].length - offset; i++) {
  35606. ar1.push(pathArray[0][i]);
  35607. ar2.push(pathArray[0][i + offset]);
  35608. }
  35609. pathArray = [ar1, ar2];
  35610. }
  35611. // positions and horizontal distances (u)
  35612. var idc = 0;
  35613. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  35614. var path;
  35615. var l;
  35616. minlg = pathArray[0].length;
  35617. var vectlg;
  35618. var dist;
  35619. for (p = 0; p < pathArray.length; p++) {
  35620. uTotalDistance[p] = 0;
  35621. us[p] = [0];
  35622. path = pathArray[p];
  35623. l = path.length;
  35624. minlg = (minlg < l) ? minlg : l;
  35625. j = 0;
  35626. while (j < l) {
  35627. positions.push(path[j].x, path[j].y, path[j].z);
  35628. if (j > 0) {
  35629. vectlg = path[j].subtract(path[j - 1]).length();
  35630. dist = vectlg + uTotalDistance[p];
  35631. us[p].push(dist);
  35632. uTotalDistance[p] = dist;
  35633. }
  35634. j++;
  35635. }
  35636. if (closePath) {
  35637. j--;
  35638. positions.push(path[0].x, path[0].y, path[0].z);
  35639. vectlg = path[j].subtract(path[0]).length();
  35640. dist = vectlg + uTotalDistance[p];
  35641. us[p].push(dist);
  35642. uTotalDistance[p] = dist;
  35643. }
  35644. lg[p] = l + closePathCorr;
  35645. idx[p] = idc;
  35646. idc += (l + closePathCorr);
  35647. }
  35648. // vertical distances (v)
  35649. var path1;
  35650. var path2;
  35651. var vertex1 = null;
  35652. var vertex2 = null;
  35653. for (i = 0; i < minlg + closePathCorr; i++) {
  35654. vTotalDistance[i] = 0;
  35655. vs[i] = [0];
  35656. for (p = 0; p < pathArray.length - 1; p++) {
  35657. path1 = pathArray[p];
  35658. path2 = pathArray[p + 1];
  35659. if (i === minlg) {
  35660. vertex1 = path1[0];
  35661. vertex2 = path2[0];
  35662. }
  35663. else {
  35664. vertex1 = path1[i];
  35665. vertex2 = path2[i];
  35666. }
  35667. vectlg = vertex2.subtract(vertex1).length();
  35668. dist = vectlg + vTotalDistance[i];
  35669. vs[i].push(dist);
  35670. vTotalDistance[i] = dist;
  35671. }
  35672. if (closeArray && vertex2 && vertex1) {
  35673. path1 = pathArray[p];
  35674. path2 = pathArray[0];
  35675. if (i === minlg) {
  35676. vertex2 = path2[0];
  35677. }
  35678. vectlg = vertex2.subtract(vertex1).length();
  35679. dist = vectlg + vTotalDistance[i];
  35680. vTotalDistance[i] = dist;
  35681. }
  35682. }
  35683. // uvs
  35684. var u;
  35685. var v;
  35686. if (customUV) {
  35687. for (p = 0; p < customUV.length; p++) {
  35688. uvs.push(customUV[p].x, customUV[p].y);
  35689. }
  35690. }
  35691. else {
  35692. for (p = 0; p < pathArray.length; p++) {
  35693. for (i = 0; i < minlg + closePathCorr; i++) {
  35694. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35695. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35696. if (invertUV) {
  35697. uvs.push(v, u);
  35698. }
  35699. else {
  35700. uvs.push(u, v);
  35701. }
  35702. }
  35703. }
  35704. }
  35705. // indices
  35706. p = 0; // path index
  35707. var pi = 0; // positions array index
  35708. var l1 = lg[p] - 1; // path1 length
  35709. var l2 = lg[p + 1] - 1; // path2 length
  35710. var min = (l1 < l2) ? l1 : l2; // current path stop index
  35711. var shft = idx[1] - idx[0]; // shift
  35712. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  35713. while (pi <= min && p < path1nb) {
  35714. // 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
  35715. indices.push(pi, pi + shft, pi + 1);
  35716. indices.push(pi + shft + 1, pi + 1, pi + shft);
  35717. pi += 1;
  35718. if (pi === min) {
  35719. p++;
  35720. if (p === lg.length - 1) {
  35721. shft = idx[0] - idx[p];
  35722. l1 = lg[p] - 1;
  35723. l2 = lg[0] - 1;
  35724. }
  35725. else {
  35726. shft = idx[p + 1] - idx[p];
  35727. l1 = lg[p] - 1;
  35728. l2 = lg[p + 1] - 1;
  35729. }
  35730. pi = idx[p];
  35731. min = (l1 < l2) ? l1 + pi : l2 + pi;
  35732. }
  35733. }
  35734. // normals
  35735. VertexData.ComputeNormals(positions, indices, normals);
  35736. if (closePath) {
  35737. var indexFirst = 0;
  35738. var indexLast = 0;
  35739. for (p = 0; p < pathArray.length; p++) {
  35740. indexFirst = idx[p] * 3;
  35741. if (p + 1 < pathArray.length) {
  35742. indexLast = (idx[p + 1] - 1) * 3;
  35743. }
  35744. else {
  35745. indexLast = normals.length - 3;
  35746. }
  35747. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  35748. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  35749. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  35750. normals[indexLast] = normals[indexFirst];
  35751. normals[indexLast + 1] = normals[indexFirst + 1];
  35752. normals[indexLast + 2] = normals[indexFirst + 2];
  35753. }
  35754. }
  35755. // sides
  35756. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35757. // Colors
  35758. var colors = null;
  35759. if (customColors) {
  35760. colors = new Float32Array(customColors.length * 4);
  35761. for (var c = 0; c < customColors.length; c++) {
  35762. colors[c * 4] = customColors[c].r;
  35763. colors[c * 4 + 1] = customColors[c].g;
  35764. colors[c * 4 + 2] = customColors[c].b;
  35765. colors[c * 4 + 3] = customColors[c].a;
  35766. }
  35767. }
  35768. // Result
  35769. var vertexData = new VertexData();
  35770. var positions32 = new Float32Array(positions);
  35771. var normals32 = new Float32Array(normals);
  35772. var uvs32 = new Float32Array(uvs);
  35773. vertexData.indices = indices;
  35774. vertexData.positions = positions32;
  35775. vertexData.normals = normals32;
  35776. vertexData.uvs = uvs32;
  35777. if (colors) {
  35778. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  35779. }
  35780. if (closePath) {
  35781. vertexData._idx = idx;
  35782. }
  35783. return vertexData;
  35784. };
  35785. /**
  35786. * Creates the VertexData of the Box.
  35787. */
  35788. VertexData.CreateBox = function (options) {
  35789. var normalsSource = [
  35790. new BABYLON.Vector3(0, 0, 1),
  35791. new BABYLON.Vector3(0, 0, -1),
  35792. new BABYLON.Vector3(1, 0, 0),
  35793. new BABYLON.Vector3(-1, 0, 0),
  35794. new BABYLON.Vector3(0, 1, 0),
  35795. new BABYLON.Vector3(0, -1, 0)
  35796. ];
  35797. var indices = [];
  35798. var positions = [];
  35799. var normals = [];
  35800. var uvs = [];
  35801. var width = options.width || options.size || 1;
  35802. var height = options.height || options.size || 1;
  35803. var depth = options.depth || options.size || 1;
  35804. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35805. var faceUV = options.faceUV || new Array(6);
  35806. var faceColors = options.faceColors;
  35807. var colors = [];
  35808. // default face colors and UV if undefined
  35809. for (var f = 0; f < 6; f++) {
  35810. if (faceUV[f] === undefined) {
  35811. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35812. }
  35813. if (faceColors && faceColors[f] === undefined) {
  35814. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35815. }
  35816. }
  35817. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  35818. // Create each face in turn.
  35819. for (var index = 0; index < normalsSource.length; index++) {
  35820. var normal = normalsSource[index];
  35821. // Get two vectors perpendicular to the face normal and to each other.
  35822. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  35823. var side2 = BABYLON.Vector3.Cross(normal, side1);
  35824. // Six indices (two triangles) per face.
  35825. var verticesLength = positions.length / 3;
  35826. indices.push(verticesLength);
  35827. indices.push(verticesLength + 1);
  35828. indices.push(verticesLength + 2);
  35829. indices.push(verticesLength);
  35830. indices.push(verticesLength + 2);
  35831. indices.push(verticesLength + 3);
  35832. // Four vertices per face.
  35833. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  35834. positions.push(vertex.x, vertex.y, vertex.z);
  35835. normals.push(normal.x, normal.y, normal.z);
  35836. uvs.push(faceUV[index].z, faceUV[index].w);
  35837. if (faceColors) {
  35838. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35839. }
  35840. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  35841. positions.push(vertex.x, vertex.y, vertex.z);
  35842. normals.push(normal.x, normal.y, normal.z);
  35843. uvs.push(faceUV[index].x, faceUV[index].w);
  35844. if (faceColors) {
  35845. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35846. }
  35847. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  35848. positions.push(vertex.x, vertex.y, vertex.z);
  35849. normals.push(normal.x, normal.y, normal.z);
  35850. uvs.push(faceUV[index].x, faceUV[index].y);
  35851. if (faceColors) {
  35852. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35853. }
  35854. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  35855. positions.push(vertex.x, vertex.y, vertex.z);
  35856. normals.push(normal.x, normal.y, normal.z);
  35857. uvs.push(faceUV[index].z, faceUV[index].y);
  35858. if (faceColors) {
  35859. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35860. }
  35861. }
  35862. // sides
  35863. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35864. // Result
  35865. var vertexData = new VertexData();
  35866. vertexData.indices = indices;
  35867. vertexData.positions = positions;
  35868. vertexData.normals = normals;
  35869. vertexData.uvs = uvs;
  35870. if (faceColors) {
  35871. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  35872. vertexData.colors = totalColors;
  35873. }
  35874. return vertexData;
  35875. };
  35876. /**
  35877. * Creates the VertexData of the Sphere.
  35878. */
  35879. VertexData.CreateSphere = function (options) {
  35880. var segments = options.segments || 32;
  35881. var diameterX = options.diameterX || options.diameter || 1;
  35882. var diameterY = options.diameterY || options.diameter || 1;
  35883. var diameterZ = options.diameterZ || options.diameter || 1;
  35884. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35885. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  35886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35887. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  35888. var totalZRotationSteps = 2 + segments;
  35889. var totalYRotationSteps = 2 * totalZRotationSteps;
  35890. var indices = [];
  35891. var positions = [];
  35892. var normals = [];
  35893. var uvs = [];
  35894. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  35895. var normalizedZ = zRotationStep / totalZRotationSteps;
  35896. var angleZ = normalizedZ * Math.PI * slice;
  35897. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  35898. var normalizedY = yRotationStep / totalYRotationSteps;
  35899. var angleY = normalizedY * Math.PI * 2 * arc;
  35900. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  35901. var rotationY = BABYLON.Matrix.RotationY(angleY);
  35902. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  35903. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  35904. var vertex = complete.multiply(radius);
  35905. var normal = complete.divide(radius).normalize();
  35906. positions.push(vertex.x, vertex.y, vertex.z);
  35907. normals.push(normal.x, normal.y, normal.z);
  35908. uvs.push(normalizedY, normalizedZ);
  35909. }
  35910. if (zRotationStep > 0) {
  35911. var verticesCount = positions.length / 3;
  35912. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  35913. indices.push((firstIndex));
  35914. indices.push((firstIndex + 1));
  35915. indices.push(firstIndex + totalYRotationSteps + 1);
  35916. indices.push((firstIndex + totalYRotationSteps + 1));
  35917. indices.push((firstIndex + 1));
  35918. indices.push((firstIndex + totalYRotationSteps + 2));
  35919. }
  35920. }
  35921. }
  35922. // Sides
  35923. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35924. // Result
  35925. var vertexData = new VertexData();
  35926. vertexData.indices = indices;
  35927. vertexData.positions = positions;
  35928. vertexData.normals = normals;
  35929. vertexData.uvs = uvs;
  35930. return vertexData;
  35931. };
  35932. /**
  35933. * Creates the VertexData of the Cylinder or Cone.
  35934. */
  35935. VertexData.CreateCylinder = function (options) {
  35936. var height = options.height || 2;
  35937. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  35938. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  35939. var tessellation = options.tessellation || 24;
  35940. var subdivisions = options.subdivisions || 1;
  35941. var hasRings = options.hasRings ? true : false;
  35942. var enclose = options.enclose ? true : false;
  35943. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35944. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35945. var faceUV = options.faceUV || new Array(3);
  35946. var faceColors = options.faceColors;
  35947. // default face colors and UV if undefined
  35948. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  35949. var ringNb = (hasRings) ? subdivisions : 1;
  35950. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  35951. var f;
  35952. for (f = 0; f < surfaceNb; f++) {
  35953. if (faceColors && faceColors[f] === undefined) {
  35954. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35955. }
  35956. }
  35957. for (f = 0; f < surfaceNb; f++) {
  35958. if (faceUV && faceUV[f] === undefined) {
  35959. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35960. }
  35961. }
  35962. var indices = new Array();
  35963. var positions = new Array();
  35964. var normals = new Array();
  35965. var uvs = new Array();
  35966. var colors = new Array();
  35967. var angle_step = Math.PI * 2 * arc / tessellation;
  35968. var angle;
  35969. var h;
  35970. var radius;
  35971. var tan = (diameterBottom - diameterTop) / 2 / height;
  35972. var ringVertex = BABYLON.Vector3.Zero();
  35973. var ringNormal = BABYLON.Vector3.Zero();
  35974. var ringFirstVertex = BABYLON.Vector3.Zero();
  35975. var ringFirstNormal = BABYLON.Vector3.Zero();
  35976. var quadNormal = BABYLON.Vector3.Zero();
  35977. var Y = BABYLON.Axis.Y;
  35978. // positions, normals, uvs
  35979. var i;
  35980. var j;
  35981. var r;
  35982. var ringIdx = 1;
  35983. var s = 1; // surface index
  35984. var cs = 0;
  35985. var v = 0;
  35986. for (i = 0; i <= subdivisions; i++) {
  35987. h = i / subdivisions;
  35988. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  35989. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  35990. for (r = 0; r < ringIdx; r++) {
  35991. if (hasRings) {
  35992. s += r;
  35993. }
  35994. if (enclose) {
  35995. s += 2 * r;
  35996. }
  35997. for (j = 0; j <= tessellation; j++) {
  35998. angle = j * angle_step;
  35999. // position
  36000. ringVertex.x = Math.cos(-angle) * radius;
  36001. ringVertex.y = -height / 2 + h * height;
  36002. ringVertex.z = Math.sin(-angle) * radius;
  36003. // normal
  36004. if (diameterTop === 0 && i === subdivisions) {
  36005. // if no top cap, reuse former normals
  36006. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36007. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36008. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36009. }
  36010. else {
  36011. ringNormal.x = ringVertex.x;
  36012. ringNormal.z = ringVertex.z;
  36013. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36014. ringNormal.normalize();
  36015. }
  36016. // keep first ring vertex values for enclose
  36017. if (j === 0) {
  36018. ringFirstVertex.copyFrom(ringVertex);
  36019. ringFirstNormal.copyFrom(ringNormal);
  36020. }
  36021. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36022. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36023. if (hasRings) {
  36024. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36025. }
  36026. else {
  36027. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36028. }
  36029. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36030. if (faceColors) {
  36031. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36032. }
  36033. }
  36034. // if enclose, add four vertices and their dedicated normals
  36035. if (arc !== 1 && enclose) {
  36036. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36037. positions.push(0, ringVertex.y, 0);
  36038. positions.push(0, ringVertex.y, 0);
  36039. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36040. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36041. quadNormal.normalize();
  36042. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36043. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36044. quadNormal.normalize();
  36045. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36046. if (hasRings) {
  36047. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36048. }
  36049. else {
  36050. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36051. }
  36052. uvs.push(faceUV[s + 1].x, v);
  36053. uvs.push(faceUV[s + 1].z, v);
  36054. if (hasRings) {
  36055. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36056. }
  36057. else {
  36058. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36059. }
  36060. uvs.push(faceUV[s + 2].x, v);
  36061. uvs.push(faceUV[s + 2].z, v);
  36062. if (faceColors) {
  36063. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36064. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36065. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36066. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36067. }
  36068. }
  36069. if (cs !== s) {
  36070. cs = s;
  36071. }
  36072. }
  36073. }
  36074. // indices
  36075. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36076. var s;
  36077. i = 0;
  36078. for (s = 0; s < subdivisions; s++) {
  36079. var i0 = 0;
  36080. var i1 = 0;
  36081. var i2 = 0;
  36082. var i3 = 0;
  36083. for (j = 0; j < tessellation; j++) {
  36084. i0 = i * (e + 1) + j;
  36085. i1 = (i + 1) * (e + 1) + j;
  36086. i2 = i * (e + 1) + (j + 1);
  36087. i3 = (i + 1) * (e + 1) + (j + 1);
  36088. indices.push(i0, i1, i2);
  36089. indices.push(i3, i2, i1);
  36090. }
  36091. if (arc !== 1 && enclose) {
  36092. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36093. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36094. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36095. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36096. }
  36097. i = (hasRings) ? (i + 2) : (i + 1);
  36098. }
  36099. // Caps
  36100. var createCylinderCap = function (isTop) {
  36101. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36102. if (radius === 0) {
  36103. return;
  36104. }
  36105. // Cap positions, normals & uvs
  36106. var angle;
  36107. var circleVector;
  36108. var i;
  36109. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36110. var c = null;
  36111. if (faceColors) {
  36112. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36113. }
  36114. // cap center
  36115. var vbase = positions.length / 3;
  36116. var offset = isTop ? height / 2 : -height / 2;
  36117. var center = new BABYLON.Vector3(0, offset, 0);
  36118. positions.push(center.x, center.y, center.z);
  36119. normals.push(0, isTop ? 1 : -1, 0);
  36120. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36121. if (c) {
  36122. colors.push(c.r, c.g, c.b, c.a);
  36123. }
  36124. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36125. for (i = 0; i <= tessellation; i++) {
  36126. angle = Math.PI * 2 * i * arc / tessellation;
  36127. var cos = Math.cos(-angle);
  36128. var sin = Math.sin(-angle);
  36129. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36130. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36131. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36132. normals.push(0, isTop ? 1 : -1, 0);
  36133. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36134. if (c) {
  36135. colors.push(c.r, c.g, c.b, c.a);
  36136. }
  36137. }
  36138. // Cap indices
  36139. for (i = 0; i < tessellation; i++) {
  36140. if (!isTop) {
  36141. indices.push(vbase);
  36142. indices.push(vbase + (i + 1));
  36143. indices.push(vbase + (i + 2));
  36144. }
  36145. else {
  36146. indices.push(vbase);
  36147. indices.push(vbase + (i + 2));
  36148. indices.push(vbase + (i + 1));
  36149. }
  36150. }
  36151. };
  36152. // add caps to geometry
  36153. createCylinderCap(false);
  36154. createCylinderCap(true);
  36155. // Sides
  36156. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36157. var vertexData = new VertexData();
  36158. vertexData.indices = indices;
  36159. vertexData.positions = positions;
  36160. vertexData.normals = normals;
  36161. vertexData.uvs = uvs;
  36162. if (faceColors) {
  36163. vertexData.colors = colors;
  36164. }
  36165. return vertexData;
  36166. };
  36167. /**
  36168. * Creates the VertexData of the Torus.
  36169. */
  36170. VertexData.CreateTorus = function (options) {
  36171. var indices = [];
  36172. var positions = [];
  36173. var normals = [];
  36174. var uvs = [];
  36175. var diameter = options.diameter || 1;
  36176. var thickness = options.thickness || 0.5;
  36177. var tessellation = options.tessellation || 16;
  36178. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36179. var stride = tessellation + 1;
  36180. for (var i = 0; i <= tessellation; i++) {
  36181. var u = i / tessellation;
  36182. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36183. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36184. for (var j = 0; j <= tessellation; j++) {
  36185. var v = 1 - j / tessellation;
  36186. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36187. var dx = Math.cos(innerAngle);
  36188. var dy = Math.sin(innerAngle);
  36189. // Create a vertex.
  36190. var normal = new BABYLON.Vector3(dx, dy, 0);
  36191. var position = normal.scale(thickness / 2);
  36192. var textureCoordinate = new BABYLON.Vector2(u, v);
  36193. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36194. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36195. positions.push(position.x, position.y, position.z);
  36196. normals.push(normal.x, normal.y, normal.z);
  36197. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36198. // And create indices for two triangles.
  36199. var nextI = (i + 1) % stride;
  36200. var nextJ = (j + 1) % stride;
  36201. indices.push(i * stride + j);
  36202. indices.push(i * stride + nextJ);
  36203. indices.push(nextI * stride + j);
  36204. indices.push(i * stride + nextJ);
  36205. indices.push(nextI * stride + nextJ);
  36206. indices.push(nextI * stride + j);
  36207. }
  36208. }
  36209. // Sides
  36210. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36211. // Result
  36212. var vertexData = new VertexData();
  36213. vertexData.indices = indices;
  36214. vertexData.positions = positions;
  36215. vertexData.normals = normals;
  36216. vertexData.uvs = uvs;
  36217. return vertexData;
  36218. };
  36219. /**
  36220. * Creates the VertexData of the LineSystem.
  36221. */
  36222. VertexData.CreateLineSystem = function (options) {
  36223. var indices = [];
  36224. var positions = [];
  36225. var lines = options.lines;
  36226. var colors = options.colors;
  36227. var vertexColors = [];
  36228. var idx = 0;
  36229. for (var l = 0; l < lines.length; l++) {
  36230. var points = lines[l];
  36231. for (var index = 0; index < points.length; index++) {
  36232. positions.push(points[index].x, points[index].y, points[index].z);
  36233. if (colors) {
  36234. var color = colors[l];
  36235. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36236. }
  36237. if (index > 0) {
  36238. indices.push(idx - 1);
  36239. indices.push(idx);
  36240. }
  36241. idx++;
  36242. }
  36243. }
  36244. var vertexData = new VertexData();
  36245. vertexData.indices = indices;
  36246. vertexData.positions = positions;
  36247. if (colors) {
  36248. vertexData.colors = vertexColors;
  36249. }
  36250. return vertexData;
  36251. };
  36252. /**
  36253. * Create the VertexData of the DashedLines.
  36254. */
  36255. VertexData.CreateDashedLines = function (options) {
  36256. var dashSize = options.dashSize || 3;
  36257. var gapSize = options.gapSize || 1;
  36258. var dashNb = options.dashNb || 200;
  36259. var points = options.points;
  36260. var positions = new Array();
  36261. var indices = new Array();
  36262. var curvect = BABYLON.Vector3.Zero();
  36263. var lg = 0;
  36264. var nb = 0;
  36265. var shft = 0;
  36266. var dashshft = 0;
  36267. var curshft = 0;
  36268. var idx = 0;
  36269. var i = 0;
  36270. for (i = 0; i < points.length - 1; i++) {
  36271. points[i + 1].subtractToRef(points[i], curvect);
  36272. lg += curvect.length();
  36273. }
  36274. shft = lg / dashNb;
  36275. dashshft = dashSize * shft / (dashSize + gapSize);
  36276. for (i = 0; i < points.length - 1; i++) {
  36277. points[i + 1].subtractToRef(points[i], curvect);
  36278. nb = Math.floor(curvect.length() / shft);
  36279. curvect.normalize();
  36280. for (var j = 0; j < nb; j++) {
  36281. curshft = shft * j;
  36282. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36283. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36284. indices.push(idx, idx + 1);
  36285. idx += 2;
  36286. }
  36287. }
  36288. // Result
  36289. var vertexData = new VertexData();
  36290. vertexData.positions = positions;
  36291. vertexData.indices = indices;
  36292. return vertexData;
  36293. };
  36294. /**
  36295. * Creates the VertexData of the Ground.
  36296. */
  36297. VertexData.CreateGround = function (options) {
  36298. var indices = [];
  36299. var positions = [];
  36300. var normals = [];
  36301. var uvs = [];
  36302. var row, col;
  36303. var width = options.width || 1;
  36304. var height = options.height || 1;
  36305. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36306. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36307. for (row = 0; row <= subdivisionsY; row++) {
  36308. for (col = 0; col <= subdivisionsX; col++) {
  36309. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36310. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36311. positions.push(position.x, position.y, position.z);
  36312. normals.push(normal.x, normal.y, normal.z);
  36313. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36314. }
  36315. }
  36316. for (row = 0; row < subdivisionsY; row++) {
  36317. for (col = 0; col < subdivisionsX; col++) {
  36318. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36319. indices.push(col + 1 + row * (subdivisionsX + 1));
  36320. indices.push(col + row * (subdivisionsX + 1));
  36321. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36322. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36323. indices.push(col + row * (subdivisionsX + 1));
  36324. }
  36325. }
  36326. // Result
  36327. var vertexData = new VertexData();
  36328. vertexData.indices = indices;
  36329. vertexData.positions = positions;
  36330. vertexData.normals = normals;
  36331. vertexData.uvs = uvs;
  36332. return vertexData;
  36333. };
  36334. /**
  36335. * Creates the VertexData of the TiledGround.
  36336. */
  36337. VertexData.CreateTiledGround = function (options) {
  36338. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36339. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36340. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36341. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36342. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36343. var precision = options.precision || { w: 1, h: 1 };
  36344. var indices = new Array();
  36345. var positions = new Array();
  36346. var normals = new Array();
  36347. var uvs = new Array();
  36348. var row, col, tileRow, tileCol;
  36349. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36350. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36351. precision.w = (precision.w < 1) ? 1 : precision.w;
  36352. precision.h = (precision.h < 1) ? 1 : precision.h;
  36353. var tileSize = {
  36354. 'w': (xmax - xmin) / subdivisions.w,
  36355. 'h': (zmax - zmin) / subdivisions.h
  36356. };
  36357. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36358. // Indices
  36359. var base = positions.length / 3;
  36360. var rowLength = precision.w + 1;
  36361. for (row = 0; row < precision.h; row++) {
  36362. for (col = 0; col < precision.w; col++) {
  36363. var square = [
  36364. base + col + row * rowLength,
  36365. base + (col + 1) + row * rowLength,
  36366. base + (col + 1) + (row + 1) * rowLength,
  36367. base + col + (row + 1) * rowLength
  36368. ];
  36369. indices.push(square[1]);
  36370. indices.push(square[2]);
  36371. indices.push(square[3]);
  36372. indices.push(square[0]);
  36373. indices.push(square[1]);
  36374. indices.push(square[3]);
  36375. }
  36376. }
  36377. // Position, normals and uvs
  36378. var position = BABYLON.Vector3.Zero();
  36379. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36380. for (row = 0; row <= precision.h; row++) {
  36381. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36382. for (col = 0; col <= precision.w; col++) {
  36383. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36384. position.y = 0;
  36385. positions.push(position.x, position.y, position.z);
  36386. normals.push(normal.x, normal.y, normal.z);
  36387. uvs.push(col / precision.w, row / precision.h);
  36388. }
  36389. }
  36390. }
  36391. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36392. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36393. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36394. }
  36395. }
  36396. // Result
  36397. var vertexData = new VertexData();
  36398. vertexData.indices = indices;
  36399. vertexData.positions = positions;
  36400. vertexData.normals = normals;
  36401. vertexData.uvs = uvs;
  36402. return vertexData;
  36403. };
  36404. /**
  36405. * Creates the VertexData of the Ground designed from a heightmap.
  36406. */
  36407. VertexData.CreateGroundFromHeightMap = function (options) {
  36408. var indices = [];
  36409. var positions = [];
  36410. var normals = [];
  36411. var uvs = [];
  36412. var row, col;
  36413. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36414. // Vertices
  36415. for (row = 0; row <= options.subdivisions; row++) {
  36416. for (col = 0; col <= options.subdivisions; col++) {
  36417. 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));
  36418. // Compute height
  36419. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36420. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36421. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36422. var r = options.buffer[pos] / 255.0;
  36423. var g = options.buffer[pos + 1] / 255.0;
  36424. var b = options.buffer[pos + 2] / 255.0;
  36425. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36426. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36427. // Add vertex
  36428. positions.push(position.x, position.y, position.z);
  36429. normals.push(0, 0, 0);
  36430. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36431. }
  36432. }
  36433. // Indices
  36434. for (row = 0; row < options.subdivisions; row++) {
  36435. for (col = 0; col < options.subdivisions; col++) {
  36436. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36437. indices.push(col + 1 + row * (options.subdivisions + 1));
  36438. indices.push(col + row * (options.subdivisions + 1));
  36439. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36440. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36441. indices.push(col + row * (options.subdivisions + 1));
  36442. }
  36443. }
  36444. // Normals
  36445. VertexData.ComputeNormals(positions, indices, normals);
  36446. // Result
  36447. var vertexData = new VertexData();
  36448. vertexData.indices = indices;
  36449. vertexData.positions = positions;
  36450. vertexData.normals = normals;
  36451. vertexData.uvs = uvs;
  36452. return vertexData;
  36453. };
  36454. /**
  36455. * Creates the VertexData of the Plane.
  36456. */
  36457. VertexData.CreatePlane = function (options) {
  36458. var indices = [];
  36459. var positions = [];
  36460. var normals = [];
  36461. var uvs = [];
  36462. var width = options.width || options.size || 1;
  36463. var height = options.height || options.size || 1;
  36464. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36465. // Vertices
  36466. var halfWidth = width / 2.0;
  36467. var halfHeight = height / 2.0;
  36468. positions.push(-halfWidth, -halfHeight, 0);
  36469. normals.push(0, 0, -1.0);
  36470. uvs.push(0.0, 0.0);
  36471. positions.push(halfWidth, -halfHeight, 0);
  36472. normals.push(0, 0, -1.0);
  36473. uvs.push(1.0, 0.0);
  36474. positions.push(halfWidth, halfHeight, 0);
  36475. normals.push(0, 0, -1.0);
  36476. uvs.push(1.0, 1.0);
  36477. positions.push(-halfWidth, halfHeight, 0);
  36478. normals.push(0, 0, -1.0);
  36479. uvs.push(0.0, 1.0);
  36480. // Indices
  36481. indices.push(0);
  36482. indices.push(1);
  36483. indices.push(2);
  36484. indices.push(0);
  36485. indices.push(2);
  36486. indices.push(3);
  36487. // Sides
  36488. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36489. // Result
  36490. var vertexData = new VertexData();
  36491. vertexData.indices = indices;
  36492. vertexData.positions = positions;
  36493. vertexData.normals = normals;
  36494. vertexData.uvs = uvs;
  36495. return vertexData;
  36496. };
  36497. /**
  36498. * Creates the VertexData of the Disc or regular Polygon.
  36499. */
  36500. VertexData.CreateDisc = function (options) {
  36501. var positions = new Array();
  36502. var indices = new Array();
  36503. var normals = new Array();
  36504. var uvs = new Array();
  36505. var radius = options.radius || 0.5;
  36506. var tessellation = options.tessellation || 64;
  36507. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36508. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36509. // positions and uvs
  36510. positions.push(0, 0, 0); // disc center first
  36511. uvs.push(0.5, 0.5);
  36512. var theta = Math.PI * 2 * arc;
  36513. var step = theta / tessellation;
  36514. for (var a = 0; a < theta; a += step) {
  36515. var x = Math.cos(a);
  36516. var y = Math.sin(a);
  36517. var u = (x + 1) / 2;
  36518. var v = (1 - y) / 2;
  36519. positions.push(radius * x, radius * y, 0);
  36520. uvs.push(u, v);
  36521. }
  36522. if (arc === 1) {
  36523. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36524. uvs.push(uvs[2], uvs[3]);
  36525. }
  36526. //indices
  36527. var vertexNb = positions.length / 3;
  36528. for (var i = 1; i < vertexNb - 1; i++) {
  36529. indices.push(i + 1, 0, i);
  36530. }
  36531. // result
  36532. VertexData.ComputeNormals(positions, indices, normals);
  36533. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36534. var vertexData = new VertexData();
  36535. vertexData.indices = indices;
  36536. vertexData.positions = positions;
  36537. vertexData.normals = normals;
  36538. vertexData.uvs = uvs;
  36539. return vertexData;
  36540. };
  36541. /**
  36542. * Re-creates the VertexData of the Polygon for sideOrientation.
  36543. */
  36544. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  36545. var faceUV = fUV || new Array(3);
  36546. var faceColors = fColors;
  36547. var colors = [];
  36548. // default face colors and UV if undefined
  36549. for (var f = 0; f < 3; f++) {
  36550. if (faceUV[f] === undefined) {
  36551. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36552. }
  36553. if (faceColors && faceColors[f] === undefined) {
  36554. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36555. }
  36556. }
  36557. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36558. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36559. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36560. var indices = polygon.getIndices();
  36561. // set face colours and textures
  36562. var idx = 0;
  36563. var face = 0;
  36564. for (var index = 0; index < normals.length; index += 3) {
  36565. //Edge Face no. 1
  36566. if (Math.abs(normals[index + 1]) < 0.001) {
  36567. face = 1;
  36568. }
  36569. //Top Face no. 0
  36570. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  36571. face = 0;
  36572. }
  36573. //Bottom Face no. 2
  36574. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  36575. face = 2;
  36576. }
  36577. idx = index / 3;
  36578. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  36579. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  36580. if (faceColors) {
  36581. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  36582. }
  36583. }
  36584. // sides
  36585. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  36586. // Result
  36587. var vertexData = new VertexData();
  36588. vertexData.indices = indices;
  36589. vertexData.positions = positions;
  36590. vertexData.normals = normals;
  36591. vertexData.uvs = uvs;
  36592. if (faceColors) {
  36593. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36594. vertexData.colors = totalColors;
  36595. }
  36596. return vertexData;
  36597. };
  36598. /**
  36599. * Creates the VertexData of the IcoSphere.
  36600. */
  36601. VertexData.CreateIcoSphere = function (options) {
  36602. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36603. var radius = options.radius || 1;
  36604. var flat = (options.flat === undefined) ? true : options.flat;
  36605. var subdivisions = options.subdivisions || 4;
  36606. var radiusX = options.radiusX || radius;
  36607. var radiusY = options.radiusY || radius;
  36608. var radiusZ = options.radiusZ || radius;
  36609. var t = (1 + Math.sqrt(5)) / 2;
  36610. // 12 vertex x,y,z
  36611. var ico_vertices = [
  36612. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36613. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36614. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36615. ];
  36616. // index of 3 vertex makes a face of icopshere
  36617. var ico_indices = [
  36618. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36619. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36620. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36621. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36622. ];
  36623. // vertex for uv have aliased position, not for UV
  36624. var vertices_unalias_id = [
  36625. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36626. // vertex alias
  36627. 0,
  36628. 2,
  36629. 3,
  36630. 3,
  36631. 3,
  36632. 4,
  36633. 7,
  36634. 8,
  36635. 9,
  36636. 9,
  36637. 10,
  36638. 11 // 23: B + 12
  36639. ];
  36640. // uv as integer step (not pixels !)
  36641. var ico_vertexuv = [
  36642. 5, 1, 3, 1, 6, 4, 0, 0,
  36643. 5, 3, 4, 2, 2, 2, 4, 0,
  36644. 2, 0, 1, 1, 6, 0, 6, 2,
  36645. // vertex alias (for same vertex on different faces)
  36646. 0, 4,
  36647. 3, 3,
  36648. 4, 4,
  36649. 3, 1,
  36650. 4, 2,
  36651. 4, 4,
  36652. 0, 2,
  36653. 1, 1,
  36654. 2, 2,
  36655. 3, 3,
  36656. 1, 3,
  36657. 2, 4 // 23: B + 12
  36658. ];
  36659. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36660. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36661. // First island of uv mapping
  36662. // v = 4h 3+ 2
  36663. // v = 3h 9+ 4
  36664. // v = 2h 9+ 5 B
  36665. // v = 1h 9 1 0
  36666. // v = 0h 3 8 7 A
  36667. // u = 0 1 2 3 4 5 6 *a
  36668. // Second island of uv mapping
  36669. // v = 4h 0+ B+ 4+
  36670. // v = 3h A+ 2+
  36671. // v = 2h 7+ 6 3+
  36672. // v = 1h 8+ 3+
  36673. // v = 0h
  36674. // u = 0 1 2 3 4 5 6 *a
  36675. // Face layout on texture UV mapping
  36676. // ============
  36677. // \ 4 /\ 16 / ======
  36678. // \ / \ / /\ 11 /
  36679. // \/ 7 \/ / \ /
  36680. // ======= / 10 \/
  36681. // /\ 17 /\ =======
  36682. // / \ / \ \ 15 /\
  36683. // / 8 \/ 12 \ \ / \
  36684. // ============ \/ 6 \
  36685. // \ 18 /\ ============
  36686. // \ / \ \ 5 /\ 0 /
  36687. // \/ 13 \ \ / \ /
  36688. // ======= \/ 1 \/
  36689. // =============
  36690. // /\ 19 /\ 2 /\
  36691. // / \ / \ / \
  36692. // / 14 \/ 9 \/ 3 \
  36693. // ===================
  36694. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36695. var ustep = 138 / 1024;
  36696. var vstep = 239 / 1024;
  36697. var uoffset = 60 / 1024;
  36698. var voffset = 26 / 1024;
  36699. // Second island should have margin, not to touch the first island
  36700. // avoid any borderline artefact in pixel rounding
  36701. var island_u_offset = -40 / 1024;
  36702. var island_v_offset = +20 / 1024;
  36703. // face is either island 0 or 1 :
  36704. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36705. var island = [
  36706. 0, 0, 0, 0, 1,
  36707. 0, 0, 1, 1, 0,
  36708. 0, 0, 1, 1, 0,
  36709. 0, 1, 1, 1, 0 // 15 - 19
  36710. ];
  36711. var indices = new Array();
  36712. var positions = new Array();
  36713. var normals = new Array();
  36714. var uvs = new Array();
  36715. var current_indice = 0;
  36716. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36717. var face_vertex_pos = new Array(3);
  36718. var face_vertex_uv = new Array(3);
  36719. var v012;
  36720. for (v012 = 0; v012 < 3; v012++) {
  36721. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36722. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36723. }
  36724. // create all with normals
  36725. for (var face = 0; face < 20; face++) {
  36726. // 3 vertex per face
  36727. for (v012 = 0; v012 < 3; v012++) {
  36728. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36729. var v_id = ico_indices[3 * face + v012];
  36730. // vertex have 3D position (x,y,z)
  36731. 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]);
  36732. // Normalize to get normal, then scale to radius
  36733. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36734. // uv Coordinates from vertex ID
  36735. 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);
  36736. }
  36737. // Subdivide the face (interpolate pos, norm, uv)
  36738. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  36739. // - norm is linear interpolation of vertex corner normal
  36740. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  36741. // - uv is linear interpolation
  36742. //
  36743. // Topology is as below for sub-divide by 2
  36744. // vertex shown as v0,v1,v2
  36745. // interp index is i1 to progress in range [v0,v1[
  36746. // interp index is i2 to progress in range [v0,v2[
  36747. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  36748. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36749. //
  36750. //
  36751. // i2 v2
  36752. // ^ ^
  36753. // / / \
  36754. // / / \
  36755. // / / \
  36756. // / / (0,1) \
  36757. // / #---------\
  36758. // / / \ (0,0)'/ \
  36759. // / / \ / \
  36760. // / / \ / \
  36761. // / / (0,0) \ / (1,0) \
  36762. // / #---------#---------\
  36763. // v0 v1
  36764. //
  36765. // --------------------> i1
  36766. //
  36767. // interp of (i1,i2):
  36768. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  36769. // along i1 : lerp(x0,x1, i1/(S-i2))
  36770. //
  36771. // centroid of triangle is needed to get help normal computation
  36772. // (c1,c2) are used for centroid location
  36773. var interp_vertex = function (i1, i2, c1, c2) {
  36774. // vertex is interpolated from
  36775. // - face_vertex_pos[0..2]
  36776. // - face_vertex_uv[0..2]
  36777. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  36778. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  36779. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  36780. pos_interp.normalize();
  36781. var vertex_normal;
  36782. if (flat) {
  36783. // in flat mode, recalculate normal as face centroid normal
  36784. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  36785. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  36786. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  36787. }
  36788. else {
  36789. // in smooth mode, recalculate normal from each single vertex position
  36790. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  36791. }
  36792. // Vertex normal need correction due to X,Y,Z radius scaling
  36793. vertex_normal.x /= radiusX;
  36794. vertex_normal.y /= radiusY;
  36795. vertex_normal.z /= radiusZ;
  36796. vertex_normal.normalize();
  36797. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  36798. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  36799. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  36800. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  36801. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  36802. uvs.push(uv_interp.x, uv_interp.y);
  36803. // push each vertex has member of a face
  36804. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  36805. indices.push(current_indice);
  36806. current_indice++;
  36807. };
  36808. for (var i2 = 0; i2 < subdivisions; i2++) {
  36809. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  36810. // face : (i1,i2) for /\ :
  36811. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  36812. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36813. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36814. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36815. if (i1 + i2 + 1 < subdivisions) {
  36816. // face : (i1,i2)' for \/ :
  36817. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36818. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36819. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36820. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36821. }
  36822. }
  36823. }
  36824. }
  36825. // Sides
  36826. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36827. // Result
  36828. var vertexData = new VertexData();
  36829. vertexData.indices = indices;
  36830. vertexData.positions = positions;
  36831. vertexData.normals = normals;
  36832. vertexData.uvs = uvs;
  36833. return vertexData;
  36834. };
  36835. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  36836. /**
  36837. * Creates the VertexData of the Polyhedron.
  36838. */
  36839. VertexData.CreatePolyhedron = function (options) {
  36840. // provided polyhedron types :
  36841. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  36842. // 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)
  36843. var polyhedra = [];
  36844. 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]] };
  36845. 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]] };
  36846. polyhedra[2] = {
  36847. 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]],
  36848. 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]]
  36849. };
  36850. polyhedra[3] = {
  36851. 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]],
  36852. 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]]
  36853. };
  36854. polyhedra[4] = {
  36855. 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]],
  36856. 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]]
  36857. };
  36858. 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]] };
  36859. 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]] };
  36860. 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]] };
  36861. 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]] };
  36862. 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]] };
  36863. 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]] };
  36864. 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]] };
  36865. 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]] };
  36866. 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]] };
  36867. polyhedra[14] = {
  36868. 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]],
  36869. 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]]
  36870. };
  36871. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  36872. var size = options.size;
  36873. var sizeX = options.sizeX || size || 1;
  36874. var sizeY = options.sizeY || size || 1;
  36875. var sizeZ = options.sizeZ || size || 1;
  36876. var data = options.custom || polyhedra[type];
  36877. var nbfaces = data.face.length;
  36878. var faceUV = options.faceUV || new Array(nbfaces);
  36879. var faceColors = options.faceColors;
  36880. var flat = (options.flat === undefined) ? true : options.flat;
  36881. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36882. var positions = new Array();
  36883. var indices = new Array();
  36884. var normals = new Array();
  36885. var uvs = new Array();
  36886. var colors = new Array();
  36887. var index = 0;
  36888. var faceIdx = 0; // face cursor in the array "indexes"
  36889. var indexes = new Array();
  36890. var i = 0;
  36891. var f = 0;
  36892. var u, v, ang, x, y, tmp;
  36893. // default face colors and UV if undefined
  36894. if (flat) {
  36895. for (f = 0; f < nbfaces; f++) {
  36896. if (faceColors && faceColors[f] === undefined) {
  36897. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36898. }
  36899. if (faceUV && faceUV[f] === undefined) {
  36900. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36901. }
  36902. }
  36903. }
  36904. if (!flat) {
  36905. for (i = 0; i < data.vertex.length; i++) {
  36906. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  36907. uvs.push(0, 0);
  36908. }
  36909. for (f = 0; f < nbfaces; f++) {
  36910. for (i = 0; i < data.face[f].length - 2; i++) {
  36911. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  36912. }
  36913. }
  36914. }
  36915. else {
  36916. for (f = 0; f < nbfaces; f++) {
  36917. var fl = data.face[f].length; // number of vertices of the current face
  36918. ang = 2 * Math.PI / fl;
  36919. x = 0.5 * Math.tan(ang / 2);
  36920. y = 0.5;
  36921. // positions, uvs, colors
  36922. for (i = 0; i < fl; i++) {
  36923. // positions
  36924. 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);
  36925. indexes.push(index);
  36926. index++;
  36927. // uvs
  36928. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  36929. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  36930. uvs.push(u, v);
  36931. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  36932. y = x * Math.sin(ang) + y * Math.cos(ang);
  36933. x = tmp;
  36934. // colors
  36935. if (faceColors) {
  36936. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  36937. }
  36938. }
  36939. // indices from indexes
  36940. for (i = 0; i < fl - 2; i++) {
  36941. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  36942. }
  36943. faceIdx += fl;
  36944. }
  36945. }
  36946. VertexData.ComputeNormals(positions, indices, normals);
  36947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36948. var vertexData = new VertexData();
  36949. vertexData.positions = positions;
  36950. vertexData.indices = indices;
  36951. vertexData.normals = normals;
  36952. vertexData.uvs = uvs;
  36953. if (faceColors && flat) {
  36954. vertexData.colors = colors;
  36955. }
  36956. return vertexData;
  36957. };
  36958. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  36959. /**
  36960. * Creates the VertexData of the Torus Knot.
  36961. */
  36962. VertexData.CreateTorusKnot = function (options) {
  36963. var indices = new Array();
  36964. var positions = new Array();
  36965. var normals = new Array();
  36966. var uvs = new Array();
  36967. var radius = options.radius || 2;
  36968. var tube = options.tube || 0.5;
  36969. var radialSegments = options.radialSegments || 32;
  36970. var tubularSegments = options.tubularSegments || 32;
  36971. var p = options.p || 2;
  36972. var q = options.q || 3;
  36973. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36974. // Helper
  36975. var getPos = function (angle) {
  36976. var cu = Math.cos(angle);
  36977. var su = Math.sin(angle);
  36978. var quOverP = q / p * angle;
  36979. var cs = Math.cos(quOverP);
  36980. var tx = radius * (2 + cs) * 0.5 * cu;
  36981. var ty = radius * (2 + cs) * su * 0.5;
  36982. var tz = radius * Math.sin(quOverP) * 0.5;
  36983. return new BABYLON.Vector3(tx, ty, tz);
  36984. };
  36985. // Vertices
  36986. var i;
  36987. var j;
  36988. for (i = 0; i <= radialSegments; i++) {
  36989. var modI = i % radialSegments;
  36990. var u = modI / radialSegments * 2 * p * Math.PI;
  36991. var p1 = getPos(u);
  36992. var p2 = getPos(u + 0.01);
  36993. var tang = p2.subtract(p1);
  36994. var n = p2.add(p1);
  36995. var bitan = BABYLON.Vector3.Cross(tang, n);
  36996. n = BABYLON.Vector3.Cross(bitan, tang);
  36997. bitan.normalize();
  36998. n.normalize();
  36999. for (j = 0; j < tubularSegments; j++) {
  37000. var modJ = j % tubularSegments;
  37001. var v = modJ / tubularSegments * 2 * Math.PI;
  37002. var cx = -tube * Math.cos(v);
  37003. var cy = tube * Math.sin(v);
  37004. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37005. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37006. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37007. uvs.push(i / radialSegments);
  37008. uvs.push(j / tubularSegments);
  37009. }
  37010. }
  37011. for (i = 0; i < radialSegments; i++) {
  37012. for (j = 0; j < tubularSegments; j++) {
  37013. var jNext = (j + 1) % tubularSegments;
  37014. var a = i * tubularSegments + j;
  37015. var b = (i + 1) * tubularSegments + j;
  37016. var c = (i + 1) * tubularSegments + jNext;
  37017. var d = i * tubularSegments + jNext;
  37018. indices.push(d);
  37019. indices.push(b);
  37020. indices.push(a);
  37021. indices.push(d);
  37022. indices.push(c);
  37023. indices.push(b);
  37024. }
  37025. }
  37026. // Normals
  37027. VertexData.ComputeNormals(positions, indices, normals);
  37028. // Sides
  37029. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37030. // Result
  37031. var vertexData = new VertexData();
  37032. vertexData.indices = indices;
  37033. vertexData.positions = positions;
  37034. vertexData.normals = normals;
  37035. vertexData.uvs = uvs;
  37036. return vertexData;
  37037. };
  37038. // Tools
  37039. /**
  37040. * @param {any} - positions (number[] or Float32Array)
  37041. * @param {any} - indices (number[] or Uint16Array)
  37042. * @param {any} - normals (number[] or Float32Array)
  37043. * options (optional) :
  37044. * facetPositions : optional array of facet positions (vector3)
  37045. * facetNormals : optional array of facet normals (vector3)
  37046. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37047. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37048. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37049. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37050. * bInfo : optional bounding info, required for facetPartitioning computation
  37051. * useRightHandedSystem: optional boolean to for right handed system computation
  37052. * depthSort : optional boolean to enable the facet depth sort computation
  37053. * distanceTo : optional Vector3 to compute the facet depth from this location
  37054. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37055. */
  37056. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37057. // temporary scalar variables
  37058. var index = 0; // facet index
  37059. var p1p2x = 0.0; // p1p2 vector x coordinate
  37060. var p1p2y = 0.0; // p1p2 vector y coordinate
  37061. var p1p2z = 0.0; // p1p2 vector z coordinate
  37062. var p3p2x = 0.0; // p3p2 vector x coordinate
  37063. var p3p2y = 0.0; // p3p2 vector y coordinate
  37064. var p3p2z = 0.0; // p3p2 vector z coordinate
  37065. var faceNormalx = 0.0; // facet normal x coordinate
  37066. var faceNormaly = 0.0; // facet normal y coordinate
  37067. var faceNormalz = 0.0; // facet normal z coordinate
  37068. var length = 0.0; // facet normal length before normalization
  37069. var v1x = 0; // vector1 x index in the positions array
  37070. var v1y = 0; // vector1 y index in the positions array
  37071. var v1z = 0; // vector1 z index in the positions array
  37072. var v2x = 0; // vector2 x index in the positions array
  37073. var v2y = 0; // vector2 y index in the positions array
  37074. var v2z = 0; // vector2 z index in the positions array
  37075. var v3x = 0; // vector3 x index in the positions array
  37076. var v3y = 0; // vector3 y index in the positions array
  37077. var v3z = 0; // vector3 z index in the positions array
  37078. var computeFacetNormals = false;
  37079. var computeFacetPositions = false;
  37080. var computeFacetPartitioning = false;
  37081. var computeDepthSort = false;
  37082. var faceNormalSign = 1;
  37083. var ratio = 0;
  37084. var distanceTo = null;
  37085. if (options) {
  37086. computeFacetNormals = (options.facetNormals) ? true : false;
  37087. computeFacetPositions = (options.facetPositions) ? true : false;
  37088. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37089. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37090. ratio = options.ratio || 0;
  37091. computeDepthSort = (options.depthSort) ? true : false;
  37092. distanceTo = (options.distanceTo);
  37093. if (computeDepthSort) {
  37094. if (distanceTo === undefined) {
  37095. distanceTo = BABYLON.Vector3.Zero();
  37096. }
  37097. var depthSortedFacets = options.depthSortedFacets;
  37098. }
  37099. }
  37100. // facetPartitioning reinit if needed
  37101. var xSubRatio = 0;
  37102. var ySubRatio = 0;
  37103. var zSubRatio = 0;
  37104. var subSq = 0;
  37105. if (computeFacetPartitioning && options && options.bbSize) {
  37106. var ox = 0; // X partitioning index for facet position
  37107. var oy = 0; // Y partinioning index for facet position
  37108. var oz = 0; // Z partinioning index for facet position
  37109. var b1x = 0; // X partitioning index for facet v1 vertex
  37110. var b1y = 0; // Y partitioning index for facet v1 vertex
  37111. var b1z = 0; // z partitioning index for facet v1 vertex
  37112. var b2x = 0; // X partitioning index for facet v2 vertex
  37113. var b2y = 0; // Y partitioning index for facet v2 vertex
  37114. var b2z = 0; // Z partitioning index for facet v2 vertex
  37115. var b3x = 0; // X partitioning index for facet v3 vertex
  37116. var b3y = 0; // Y partitioning index for facet v3 vertex
  37117. var b3z = 0; // Z partitioning index for facet v3 vertex
  37118. var block_idx_o = 0; // facet barycenter block index
  37119. var block_idx_v1 = 0; // v1 vertex block index
  37120. var block_idx_v2 = 0; // v2 vertex block index
  37121. var block_idx_v3 = 0; // v3 vertex block index
  37122. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37123. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37124. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37125. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37126. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37127. subSq = options.subDiv.max * options.subDiv.max;
  37128. options.facetPartitioning.length = 0;
  37129. }
  37130. // reset the normals
  37131. for (index = 0; index < positions.length; index++) {
  37132. normals[index] = 0.0;
  37133. }
  37134. // Loop : 1 indice triplet = 1 facet
  37135. var nbFaces = (indices.length / 3) | 0;
  37136. for (index = 0; index < nbFaces; index++) {
  37137. // get the indexes of the coordinates of each vertex of the facet
  37138. v1x = indices[index * 3] * 3;
  37139. v1y = v1x + 1;
  37140. v1z = v1x + 2;
  37141. v2x = indices[index * 3 + 1] * 3;
  37142. v2y = v2x + 1;
  37143. v2z = v2x + 2;
  37144. v3x = indices[index * 3 + 2] * 3;
  37145. v3y = v3x + 1;
  37146. v3z = v3x + 2;
  37147. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37148. p1p2y = positions[v1y] - positions[v2y];
  37149. p1p2z = positions[v1z] - positions[v2z];
  37150. p3p2x = positions[v3x] - positions[v2x];
  37151. p3p2y = positions[v3y] - positions[v2y];
  37152. p3p2z = positions[v3z] - positions[v2z];
  37153. // compute the face normal with the cross product
  37154. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37155. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37156. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37157. // normalize this normal and store it in the array facetData
  37158. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37159. length = (length === 0) ? 1.0 : length;
  37160. faceNormalx /= length;
  37161. faceNormaly /= length;
  37162. faceNormalz /= length;
  37163. if (computeFacetNormals && options) {
  37164. options.facetNormals[index].x = faceNormalx;
  37165. options.facetNormals[index].y = faceNormaly;
  37166. options.facetNormals[index].z = faceNormalz;
  37167. }
  37168. if (computeFacetPositions && options) {
  37169. // compute and the facet barycenter coordinates in the array facetPositions
  37170. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37171. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37172. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37173. }
  37174. if (computeFacetPartitioning && options) {
  37175. // store the facet indexes in arrays in the main facetPartitioning array :
  37176. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37177. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37178. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37179. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37180. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37181. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37182. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37183. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37184. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37185. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37186. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37187. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37188. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37189. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37190. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37191. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37192. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37193. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37194. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37195. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37196. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37197. // push each facet index in each block containing the vertex
  37198. options.facetPartitioning[block_idx_v1].push(index);
  37199. if (block_idx_v2 != block_idx_v1) {
  37200. options.facetPartitioning[block_idx_v2].push(index);
  37201. }
  37202. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37203. options.facetPartitioning[block_idx_v3].push(index);
  37204. }
  37205. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37206. options.facetPartitioning[block_idx_o].push(index);
  37207. }
  37208. }
  37209. if (computeDepthSort && options && options.facetPositions) {
  37210. var dsf = depthSortedFacets[index];
  37211. dsf.ind = index * 3;
  37212. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37213. }
  37214. // compute the normals anyway
  37215. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37216. normals[v1y] += faceNormaly;
  37217. normals[v1z] += faceNormalz;
  37218. normals[v2x] += faceNormalx;
  37219. normals[v2y] += faceNormaly;
  37220. normals[v2z] += faceNormalz;
  37221. normals[v3x] += faceNormalx;
  37222. normals[v3y] += faceNormaly;
  37223. normals[v3z] += faceNormalz;
  37224. }
  37225. // last normalization of each normal
  37226. for (index = 0; index < normals.length / 3; index++) {
  37227. faceNormalx = normals[index * 3];
  37228. faceNormaly = normals[index * 3 + 1];
  37229. faceNormalz = normals[index * 3 + 2];
  37230. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37231. length = (length === 0) ? 1.0 : length;
  37232. faceNormalx /= length;
  37233. faceNormaly /= length;
  37234. faceNormalz /= length;
  37235. normals[index * 3] = faceNormalx;
  37236. normals[index * 3 + 1] = faceNormaly;
  37237. normals[index * 3 + 2] = faceNormalz;
  37238. }
  37239. };
  37240. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37241. var li = indices.length;
  37242. var ln = normals.length;
  37243. var i;
  37244. var n;
  37245. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37246. switch (sideOrientation) {
  37247. case BABYLON.Mesh.FRONTSIDE:
  37248. // nothing changed
  37249. break;
  37250. case BABYLON.Mesh.BACKSIDE:
  37251. var tmp;
  37252. // indices
  37253. for (i = 0; i < li; i += 3) {
  37254. tmp = indices[i];
  37255. indices[i] = indices[i + 2];
  37256. indices[i + 2] = tmp;
  37257. }
  37258. // normals
  37259. for (n = 0; n < ln; n++) {
  37260. normals[n] = -normals[n];
  37261. }
  37262. break;
  37263. case BABYLON.Mesh.DOUBLESIDE:
  37264. // positions
  37265. var lp = positions.length;
  37266. var l = lp / 3;
  37267. for (var p = 0; p < lp; p++) {
  37268. positions[lp + p] = positions[p];
  37269. }
  37270. // indices
  37271. for (i = 0; i < li; i += 3) {
  37272. indices[i + li] = indices[i + 2] + l;
  37273. indices[i + 1 + li] = indices[i + 1] + l;
  37274. indices[i + 2 + li] = indices[i] + l;
  37275. }
  37276. // normals
  37277. for (n = 0; n < ln; n++) {
  37278. normals[ln + n] = -normals[n];
  37279. }
  37280. // uvs
  37281. var lu = uvs.length;
  37282. var u = 0;
  37283. for (u = 0; u < lu; u++) {
  37284. uvs[u + lu] = uvs[u];
  37285. }
  37286. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37287. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37288. u = 0;
  37289. for (i = 0; i < lu / 2; i++) {
  37290. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37291. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37292. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37293. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37294. u += 2;
  37295. }
  37296. break;
  37297. }
  37298. };
  37299. /**
  37300. * Creates a new VertexData from the imported parameters.
  37301. */
  37302. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37303. var vertexData = new VertexData();
  37304. // positions
  37305. var positions = parsedVertexData.positions;
  37306. if (positions) {
  37307. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37308. }
  37309. // normals
  37310. var normals = parsedVertexData.normals;
  37311. if (normals) {
  37312. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37313. }
  37314. // tangents
  37315. var tangents = parsedVertexData.tangents;
  37316. if (tangents) {
  37317. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37318. }
  37319. // uvs
  37320. var uvs = parsedVertexData.uvs;
  37321. if (uvs) {
  37322. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37323. }
  37324. // uv2s
  37325. var uv2s = parsedVertexData.uv2s;
  37326. if (uv2s) {
  37327. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37328. }
  37329. // uv3s
  37330. var uv3s = parsedVertexData.uv3s;
  37331. if (uv3s) {
  37332. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37333. }
  37334. // uv4s
  37335. var uv4s = parsedVertexData.uv4s;
  37336. if (uv4s) {
  37337. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37338. }
  37339. // uv5s
  37340. var uv5s = parsedVertexData.uv5s;
  37341. if (uv5s) {
  37342. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37343. }
  37344. // uv6s
  37345. var uv6s = parsedVertexData.uv6s;
  37346. if (uv6s) {
  37347. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37348. }
  37349. // colors
  37350. var colors = parsedVertexData.colors;
  37351. if (colors) {
  37352. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37353. }
  37354. // matricesIndices
  37355. var matricesIndices = parsedVertexData.matricesIndices;
  37356. if (matricesIndices) {
  37357. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37358. }
  37359. // matricesWeights
  37360. var matricesWeights = parsedVertexData.matricesWeights;
  37361. if (matricesWeights) {
  37362. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37363. }
  37364. // indices
  37365. var indices = parsedVertexData.indices;
  37366. if (indices) {
  37367. vertexData.indices = indices;
  37368. }
  37369. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37370. };
  37371. return VertexData;
  37372. }());
  37373. BABYLON.VertexData = VertexData;
  37374. })(BABYLON || (BABYLON = {}));
  37375. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37376. "use strict";
  37377. var BABYLON;
  37378. (function (BABYLON) {
  37379. /**
  37380. * Class used to store geometry data (vertex buffers + index buffer)
  37381. */
  37382. var Geometry = /** @class */ (function () {
  37383. /**
  37384. * Creates a new geometry
  37385. * @param id defines the unique ID
  37386. * @param scene defines the hosting scene
  37387. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37388. * @param updatable defines if geometry must be updatable (false by default)
  37389. * @param mesh defines the mesh that will be associated with the geometry
  37390. */
  37391. function Geometry(id, scene, vertexData, updatable, mesh) {
  37392. if (updatable === void 0) { updatable = false; }
  37393. if (mesh === void 0) { mesh = null; }
  37394. /**
  37395. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37396. */
  37397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37398. this._totalVertices = 0;
  37399. this._isDisposed = false;
  37400. this._indexBufferIsUpdatable = false;
  37401. this.id = id;
  37402. this._engine = scene.getEngine();
  37403. this._meshes = [];
  37404. this._scene = scene;
  37405. //Init vertex buffer cache
  37406. this._vertexBuffers = {};
  37407. this._indices = [];
  37408. this._updatable = updatable;
  37409. // vertexData
  37410. if (vertexData) {
  37411. this.setAllVerticesData(vertexData, updatable);
  37412. }
  37413. else {
  37414. this._totalVertices = 0;
  37415. this._indices = [];
  37416. }
  37417. if (this._engine.getCaps().vertexArrayObject) {
  37418. this._vertexArrayObjects = {};
  37419. }
  37420. // applyToMesh
  37421. if (mesh) {
  37422. if (mesh.getClassName() === "LinesMesh") {
  37423. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37424. this._updateExtend();
  37425. }
  37426. this.applyToMesh(mesh);
  37427. mesh.computeWorldMatrix(true);
  37428. }
  37429. }
  37430. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37431. /**
  37432. * 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
  37433. */
  37434. get: function () {
  37435. return this._boundingBias;
  37436. },
  37437. /**
  37438. * 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
  37439. */
  37440. set: function (value) {
  37441. if (this._boundingBias && this._boundingBias.equals(value)) {
  37442. return;
  37443. }
  37444. this._boundingBias = value.clone();
  37445. this._updateBoundingInfo(true, null);
  37446. },
  37447. enumerable: true,
  37448. configurable: true
  37449. });
  37450. /**
  37451. * Static function used to attach a new empty geometry to a mesh
  37452. * @param mesh defines the mesh to attach the geometry to
  37453. * @returns the new {BABYLON.Geometry}
  37454. */
  37455. Geometry.CreateGeometryForMesh = function (mesh) {
  37456. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  37457. geometry.applyToMesh(mesh);
  37458. return geometry;
  37459. };
  37460. Object.defineProperty(Geometry.prototype, "extend", {
  37461. /**
  37462. * Gets the current extend of the geometry
  37463. */
  37464. get: function () {
  37465. return this._extend;
  37466. },
  37467. enumerable: true,
  37468. configurable: true
  37469. });
  37470. /**
  37471. * Gets the hosting scene
  37472. * @returns the hosting {BABYLON.Scene}
  37473. */
  37474. Geometry.prototype.getScene = function () {
  37475. return this._scene;
  37476. };
  37477. /**
  37478. * Gets the hosting engine
  37479. * @returns the hosting {BABYLON.Engine}
  37480. */
  37481. Geometry.prototype.getEngine = function () {
  37482. return this._engine;
  37483. };
  37484. /**
  37485. * Defines if the geometry is ready to use
  37486. * @returns true if the geometry is ready to be used
  37487. */
  37488. Geometry.prototype.isReady = function () {
  37489. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37490. };
  37491. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37492. /**
  37493. * Gets a value indicating that the geometry should not be serialized
  37494. */
  37495. get: function () {
  37496. for (var index = 0; index < this._meshes.length; index++) {
  37497. if (!this._meshes[index].doNotSerialize) {
  37498. return false;
  37499. }
  37500. }
  37501. return true;
  37502. },
  37503. enumerable: true,
  37504. configurable: true
  37505. });
  37506. /** @ignore */
  37507. Geometry.prototype._rebuild = function () {
  37508. if (this._vertexArrayObjects) {
  37509. this._vertexArrayObjects = {};
  37510. }
  37511. // Index buffer
  37512. if (this._meshes.length !== 0 && this._indices) {
  37513. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37514. }
  37515. // Vertex buffers
  37516. for (var key in this._vertexBuffers) {
  37517. var vertexBuffer = this._vertexBuffers[key];
  37518. vertexBuffer._rebuild();
  37519. }
  37520. };
  37521. /**
  37522. * Affects all gemetry data in one call
  37523. * @param vertexData defines the geometry data
  37524. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  37525. */
  37526. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37527. vertexData.applyToGeometry(this, updatable);
  37528. this.notifyUpdate();
  37529. };
  37530. /**
  37531. * Set specific vertex data
  37532. * @param kind defines the data kind (Position, normal, etc...)
  37533. * @param data defines the vertex data to use
  37534. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  37535. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  37536. */
  37537. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37538. if (updatable === void 0) { updatable = false; }
  37539. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37540. this._totalVertices = data.length / (stride || 3);
  37541. }
  37542. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37543. this.setVerticesBuffer(buffer);
  37544. };
  37545. /**
  37546. * Removes a specific vertex data
  37547. * @param kind defines the data kind (Position, normal, etc...)
  37548. */
  37549. Geometry.prototype.removeVerticesData = function (kind) {
  37550. if (this._vertexBuffers[kind]) {
  37551. this._vertexBuffers[kind].dispose();
  37552. delete this._vertexBuffers[kind];
  37553. }
  37554. };
  37555. /**
  37556. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  37557. * @param buffer defines the vertex buffer to use
  37558. * @param totalVertices defines the total number of vertices for position kind (could be null)
  37559. */
  37560. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  37561. if (totalVertices === void 0) { totalVertices = null; }
  37562. var kind = buffer.getKind();
  37563. if (this._vertexBuffers[kind]) {
  37564. this._vertexBuffers[kind].dispose();
  37565. }
  37566. this._vertexBuffers[kind] = buffer;
  37567. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37568. if (totalVertices != null) {
  37569. this._totalVertices = totalVertices;
  37570. }
  37571. this._updateExtend();
  37572. this._resetPointsArrayCache();
  37573. var meshes = this._meshes;
  37574. var numOfMeshes = meshes.length;
  37575. for (var index = 0; index < numOfMeshes; index++) {
  37576. var mesh = meshes[index];
  37577. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37578. mesh._createGlobalSubMesh(false);
  37579. mesh.computeWorldMatrix(true);
  37580. }
  37581. }
  37582. this.notifyUpdate(kind);
  37583. if (this._vertexArrayObjects) {
  37584. this._disposeVertexArrayObjects();
  37585. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37586. }
  37587. };
  37588. /**
  37589. * Update a specific vertex buffer
  37590. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  37591. * It will do nothing if the buffer is not updatable
  37592. * @param kind defines the data kind (Position, normal, etc...)
  37593. * @param data defines the data to use
  37594. * @param offset defines the offset in the target buffer where to store the data
  37595. */
  37596. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37597. var vertexBuffer = this.getVertexBuffer(kind);
  37598. if (!vertexBuffer) {
  37599. return;
  37600. }
  37601. vertexBuffer.updateDirectly(data, offset);
  37602. this.notifyUpdate(kind);
  37603. };
  37604. /**
  37605. * Update a specific vertex buffer
  37606. * This function will create a new buffer if the current one is not updatable
  37607. * @param kind defines the data kind (Position, normal, etc...)
  37608. * @param data defines the data to use
  37609. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  37610. */
  37611. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37612. if (updateExtends === void 0) { updateExtends = false; }
  37613. var vertexBuffer = this.getVertexBuffer(kind);
  37614. if (!vertexBuffer) {
  37615. return;
  37616. }
  37617. vertexBuffer.update(data);
  37618. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37619. this._updateBoundingInfo(updateExtends, data);
  37620. }
  37621. this.notifyUpdate(kind);
  37622. };
  37623. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  37624. if (updateExtends) {
  37625. this._updateExtend(data);
  37626. }
  37627. var meshes = this._meshes;
  37628. var numOfMeshes = meshes.length;
  37629. this._resetPointsArrayCache();
  37630. for (var index = 0; index < numOfMeshes; index++) {
  37631. var mesh = meshes[index];
  37632. if (updateExtends) {
  37633. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37634. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37635. var subMesh = mesh.subMeshes[subIndex];
  37636. subMesh.refreshBoundingInfo();
  37637. }
  37638. }
  37639. }
  37640. };
  37641. /** @ignore */
  37642. Geometry.prototype._bind = function (effect, indexToBind) {
  37643. if (!effect) {
  37644. return;
  37645. }
  37646. if (indexToBind === undefined) {
  37647. indexToBind = this._indexBuffer;
  37648. }
  37649. var vbs = this.getVertexBuffers();
  37650. if (!vbs) {
  37651. return;
  37652. }
  37653. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37654. this._engine.bindBuffers(vbs, indexToBind, effect);
  37655. return;
  37656. }
  37657. // Using VAO
  37658. if (!this._vertexArrayObjects[effect.key]) {
  37659. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  37660. }
  37661. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37662. };
  37663. /**
  37664. * Gets total number of vertices
  37665. * @returns the total number of vertices
  37666. */
  37667. Geometry.prototype.getTotalVertices = function () {
  37668. if (!this.isReady()) {
  37669. return 0;
  37670. }
  37671. return this._totalVertices;
  37672. };
  37673. /**
  37674. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  37675. * @param kind defines the data kind (Position, normal, etc...)
  37676. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37677. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  37678. * @returns a float array containing vertex data
  37679. */
  37680. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  37681. var vertexBuffer = this.getVertexBuffer(kind);
  37682. if (!vertexBuffer) {
  37683. return null;
  37684. }
  37685. var data = vertexBuffer.getData();
  37686. if (!data) {
  37687. return null;
  37688. }
  37689. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  37690. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  37691. var count = this._totalVertices * defaultStride;
  37692. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  37693. var copy_1 = new Array(count);
  37694. vertexBuffer.forEach(count, function (value, index) {
  37695. copy_1[index] = value;
  37696. });
  37697. return copy_1;
  37698. }
  37699. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  37700. if (data instanceof Array) {
  37701. var offset = vertexBuffer.byteOffset / 4;
  37702. return BABYLON.Tools.Slice(data, offset, offset + count);
  37703. }
  37704. else if (data instanceof ArrayBuffer) {
  37705. return new Float32Array(data, vertexBuffer.byteOffset, count);
  37706. }
  37707. else {
  37708. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  37709. }
  37710. }
  37711. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  37712. return BABYLON.Tools.Slice(data);
  37713. }
  37714. return data;
  37715. };
  37716. /**
  37717. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  37718. * @param kind defines the data kind (Position, normal, etc...)
  37719. * @returns true if the vertex buffer with the specified kind is updatable
  37720. */
  37721. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  37722. var vb = this._vertexBuffers[kind];
  37723. if (!vb) {
  37724. return false;
  37725. }
  37726. return vb.isUpdatable();
  37727. };
  37728. /**
  37729. * Gets a specific vertex buffer
  37730. * @param kind defines the data kind (Position, normal, etc...)
  37731. * @returns a {BABYLON.VertexBuffer}
  37732. */
  37733. Geometry.prototype.getVertexBuffer = function (kind) {
  37734. if (!this.isReady()) {
  37735. return null;
  37736. }
  37737. return this._vertexBuffers[kind];
  37738. };
  37739. /**
  37740. * Returns all vertex buffers
  37741. * @return an object holding all vertex buffers indexed by kind
  37742. */
  37743. Geometry.prototype.getVertexBuffers = function () {
  37744. if (!this.isReady()) {
  37745. return null;
  37746. }
  37747. return this._vertexBuffers;
  37748. };
  37749. /**
  37750. * Gets a boolean indicating if specific vertex buffer is present
  37751. * @param kind defines the data kind (Position, normal, etc...)
  37752. * @returns true if data is present
  37753. */
  37754. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37755. if (!this._vertexBuffers) {
  37756. if (this._delayInfo) {
  37757. return this._delayInfo.indexOf(kind) !== -1;
  37758. }
  37759. return false;
  37760. }
  37761. return this._vertexBuffers[kind] !== undefined;
  37762. };
  37763. /**
  37764. * Gets a list of all attached data kinds (Position, normal, etc...)
  37765. * @returns a list of string containing all kinds
  37766. */
  37767. Geometry.prototype.getVerticesDataKinds = function () {
  37768. var result = [];
  37769. var kind;
  37770. if (!this._vertexBuffers && this._delayInfo) {
  37771. for (kind in this._delayInfo) {
  37772. result.push(kind);
  37773. }
  37774. }
  37775. else {
  37776. for (kind in this._vertexBuffers) {
  37777. result.push(kind);
  37778. }
  37779. }
  37780. return result;
  37781. };
  37782. /**
  37783. * Update index buffer
  37784. * @param indices defines the indices to store in the index buffer
  37785. * @param offset defines the offset in the target buffer where to store the data
  37786. */
  37787. Geometry.prototype.updateIndices = function (indices, offset) {
  37788. if (!this._indexBuffer) {
  37789. return;
  37790. }
  37791. if (!this._indexBufferIsUpdatable) {
  37792. this.setIndices(indices, null, true);
  37793. }
  37794. else {
  37795. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  37796. }
  37797. };
  37798. /**
  37799. * Creates a new index buffer
  37800. * @param indices defines the indices to store in the index buffer
  37801. * @param totalVertices defines the total number of vertices (could be null)
  37802. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  37803. */
  37804. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  37805. if (totalVertices === void 0) { totalVertices = null; }
  37806. if (updatable === void 0) { updatable = false; }
  37807. if (this._indexBuffer) {
  37808. this._engine._releaseBuffer(this._indexBuffer);
  37809. }
  37810. this._disposeVertexArrayObjects();
  37811. this._indices = indices;
  37812. this._indexBufferIsUpdatable = updatable;
  37813. if (this._meshes.length !== 0 && this._indices) {
  37814. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  37815. }
  37816. if (totalVertices != undefined) {
  37817. this._totalVertices = totalVertices;
  37818. }
  37819. var meshes = this._meshes;
  37820. var numOfMeshes = meshes.length;
  37821. for (var index = 0; index < numOfMeshes; index++) {
  37822. meshes[index]._createGlobalSubMesh(true);
  37823. }
  37824. this.notifyUpdate();
  37825. };
  37826. /**
  37827. * Return the total number of indices
  37828. * @returns the total number of indices
  37829. */
  37830. Geometry.prototype.getTotalIndices = function () {
  37831. if (!this.isReady()) {
  37832. return 0;
  37833. }
  37834. return this._indices.length;
  37835. };
  37836. /**
  37837. * Gets the index buffer array
  37838. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37839. * @returns the index buffer array
  37840. */
  37841. Geometry.prototype.getIndices = function (copyWhenShared) {
  37842. if (!this.isReady()) {
  37843. return null;
  37844. }
  37845. var orig = this._indices;
  37846. if (!copyWhenShared || this._meshes.length === 1) {
  37847. return orig;
  37848. }
  37849. else {
  37850. var len = orig.length;
  37851. var copy = [];
  37852. for (var i = 0; i < len; i++) {
  37853. copy.push(orig[i]);
  37854. }
  37855. return copy;
  37856. }
  37857. };
  37858. /**
  37859. * Gets the index buffer
  37860. * @return the index buffer
  37861. */
  37862. Geometry.prototype.getIndexBuffer = function () {
  37863. if (!this.isReady()) {
  37864. return null;
  37865. }
  37866. return this._indexBuffer;
  37867. };
  37868. /** @ignore */
  37869. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  37870. if (effect === void 0) { effect = null; }
  37871. if (!effect || !this._vertexArrayObjects) {
  37872. return;
  37873. }
  37874. if (this._vertexArrayObjects[effect.key]) {
  37875. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  37876. delete this._vertexArrayObjects[effect.key];
  37877. }
  37878. };
  37879. /**
  37880. * Release the associated resources for a specific mesh
  37881. * @param mesh defines the source mesh
  37882. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  37883. */
  37884. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37885. var meshes = this._meshes;
  37886. var index = meshes.indexOf(mesh);
  37887. if (index === -1) {
  37888. return;
  37889. }
  37890. meshes.splice(index, 1);
  37891. mesh._geometry = null;
  37892. if (meshes.length === 0 && shouldDispose) {
  37893. this.dispose();
  37894. }
  37895. };
  37896. /**
  37897. * Apply current geometry to a given mesh
  37898. * @param mesh defines the mesh to apply geometry to
  37899. */
  37900. Geometry.prototype.applyToMesh = function (mesh) {
  37901. if (mesh._geometry === this) {
  37902. return;
  37903. }
  37904. var previousGeometry = mesh._geometry;
  37905. if (previousGeometry) {
  37906. previousGeometry.releaseForMesh(mesh);
  37907. }
  37908. var meshes = this._meshes;
  37909. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37910. mesh._geometry = this;
  37911. this._scene.pushGeometry(this);
  37912. meshes.push(mesh);
  37913. if (this.isReady()) {
  37914. this._applyToMesh(mesh);
  37915. }
  37916. else {
  37917. mesh._boundingInfo = this._boundingInfo;
  37918. }
  37919. };
  37920. Geometry.prototype._updateExtend = function (data) {
  37921. if (data === void 0) { data = null; }
  37922. if (!data) {
  37923. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37924. }
  37925. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  37926. };
  37927. Geometry.prototype._applyToMesh = function (mesh) {
  37928. var numOfMeshes = this._meshes.length;
  37929. // vertexBuffers
  37930. for (var kind in this._vertexBuffers) {
  37931. if (numOfMeshes === 1) {
  37932. this._vertexBuffers[kind].create();
  37933. }
  37934. var buffer = this._vertexBuffers[kind].getBuffer();
  37935. if (buffer)
  37936. buffer.references = numOfMeshes;
  37937. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37938. if (!this._extend) {
  37939. this._updateExtend();
  37940. }
  37941. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37942. mesh._createGlobalSubMesh(false);
  37943. //bounding info was just created again, world matrix should be applied again.
  37944. mesh._updateBoundingInfo();
  37945. }
  37946. }
  37947. // indexBuffer
  37948. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37949. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37950. }
  37951. if (this._indexBuffer) {
  37952. this._indexBuffer.references = numOfMeshes;
  37953. }
  37954. };
  37955. Geometry.prototype.notifyUpdate = function (kind) {
  37956. if (this.onGeometryUpdated) {
  37957. this.onGeometryUpdated(this, kind);
  37958. }
  37959. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  37960. var mesh = _a[_i];
  37961. mesh._markSubMeshesAsAttributesDirty();
  37962. }
  37963. };
  37964. /**
  37965. * Load the geometry if it was flagged as delay loaded
  37966. * @param scene defines the hosting scene
  37967. * @param onLoaded defines a callback called when the geometry is loaded
  37968. */
  37969. Geometry.prototype.load = function (scene, onLoaded) {
  37970. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37971. return;
  37972. }
  37973. if (this.isReady()) {
  37974. if (onLoaded) {
  37975. onLoaded();
  37976. }
  37977. return;
  37978. }
  37979. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37980. this._queueLoad(scene, onLoaded);
  37981. };
  37982. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37983. var _this = this;
  37984. if (!this.delayLoadingFile) {
  37985. return;
  37986. }
  37987. scene._addPendingData(this);
  37988. scene._loadFile(this.delayLoadingFile, function (data) {
  37989. if (!_this._delayLoadingFunction) {
  37990. return;
  37991. }
  37992. _this._delayLoadingFunction(JSON.parse(data), _this);
  37993. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37994. _this._delayInfo = [];
  37995. scene._removePendingData(_this);
  37996. var meshes = _this._meshes;
  37997. var numOfMeshes = meshes.length;
  37998. for (var index = 0; index < numOfMeshes; index++) {
  37999. _this._applyToMesh(meshes[index]);
  38000. }
  38001. if (onLoaded) {
  38002. onLoaded();
  38003. }
  38004. }, undefined, true);
  38005. };
  38006. /**
  38007. * Invert the geometry to move from a right handed system to a left handed one.
  38008. */
  38009. Geometry.prototype.toLeftHanded = function () {
  38010. // Flip faces
  38011. var tIndices = this.getIndices(false);
  38012. if (tIndices != null && tIndices.length > 0) {
  38013. for (var i = 0; i < tIndices.length; i += 3) {
  38014. var tTemp = tIndices[i + 0];
  38015. tIndices[i + 0] = tIndices[i + 2];
  38016. tIndices[i + 2] = tTemp;
  38017. }
  38018. this.setIndices(tIndices);
  38019. }
  38020. // Negate position.z
  38021. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38022. if (tPositions != null && tPositions.length > 0) {
  38023. for (var i = 0; i < tPositions.length; i += 3) {
  38024. tPositions[i + 2] = -tPositions[i + 2];
  38025. }
  38026. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38027. }
  38028. // Negate normal.z
  38029. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38030. if (tNormals != null && tNormals.length > 0) {
  38031. for (var i = 0; i < tNormals.length; i += 3) {
  38032. tNormals[i + 2] = -tNormals[i + 2];
  38033. }
  38034. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38035. }
  38036. };
  38037. // Cache
  38038. /** @ignore */
  38039. Geometry.prototype._resetPointsArrayCache = function () {
  38040. this._positions = null;
  38041. };
  38042. /** @ignore */
  38043. Geometry.prototype._generatePointsArray = function () {
  38044. if (this._positions)
  38045. return true;
  38046. this._positions = [];
  38047. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38048. if (!data) {
  38049. return false;
  38050. }
  38051. for (var index = 0; index < data.length; index += 3) {
  38052. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38053. }
  38054. return true;
  38055. };
  38056. /**
  38057. * Gets a value indicating if the geometry is disposed
  38058. * @returns true if the geometry was disposed
  38059. */
  38060. Geometry.prototype.isDisposed = function () {
  38061. return this._isDisposed;
  38062. };
  38063. Geometry.prototype._disposeVertexArrayObjects = function () {
  38064. if (this._vertexArrayObjects) {
  38065. for (var kind in this._vertexArrayObjects) {
  38066. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38067. }
  38068. this._vertexArrayObjects = {};
  38069. }
  38070. };
  38071. /**
  38072. * Free all associated resources
  38073. */
  38074. Geometry.prototype.dispose = function () {
  38075. var meshes = this._meshes;
  38076. var numOfMeshes = meshes.length;
  38077. var index;
  38078. for (index = 0; index < numOfMeshes; index++) {
  38079. this.releaseForMesh(meshes[index]);
  38080. }
  38081. this._meshes = [];
  38082. this._disposeVertexArrayObjects();
  38083. for (var kind in this._vertexBuffers) {
  38084. this._vertexBuffers[kind].dispose();
  38085. }
  38086. this._vertexBuffers = {};
  38087. this._totalVertices = 0;
  38088. if (this._indexBuffer) {
  38089. this._engine._releaseBuffer(this._indexBuffer);
  38090. }
  38091. this._indexBuffer = null;
  38092. this._indices = [];
  38093. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38094. this.delayLoadingFile = null;
  38095. this._delayLoadingFunction = null;
  38096. this._delayInfo = [];
  38097. this._boundingInfo = null;
  38098. this._scene.removeGeometry(this);
  38099. this._isDisposed = true;
  38100. };
  38101. /**
  38102. * Clone the current geometry into a new geometry
  38103. * @param id defines the unique ID of the new geometry
  38104. * @returns a new geometry object
  38105. */
  38106. Geometry.prototype.copy = function (id) {
  38107. var vertexData = new BABYLON.VertexData();
  38108. vertexData.indices = [];
  38109. var indices = this.getIndices();
  38110. if (indices) {
  38111. for (var index = 0; index < indices.length; index++) {
  38112. vertexData.indices.push(indices[index]);
  38113. }
  38114. }
  38115. var updatable = false;
  38116. var stopChecking = false;
  38117. var kind;
  38118. for (kind in this._vertexBuffers) {
  38119. // using slice() to make a copy of the array and not just reference it
  38120. var data = this.getVerticesData(kind);
  38121. if (data instanceof Float32Array) {
  38122. vertexData.set(new Float32Array(data), kind);
  38123. }
  38124. else {
  38125. vertexData.set(data.slice(0), kind);
  38126. }
  38127. if (!stopChecking) {
  38128. var vb = this.getVertexBuffer(kind);
  38129. if (vb) {
  38130. updatable = vb.isUpdatable();
  38131. stopChecking = !updatable;
  38132. }
  38133. }
  38134. }
  38135. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38136. geometry.delayLoadState = this.delayLoadState;
  38137. geometry.delayLoadingFile = this.delayLoadingFile;
  38138. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38139. for (kind in this._delayInfo) {
  38140. geometry._delayInfo = geometry._delayInfo || [];
  38141. geometry._delayInfo.push(kind);
  38142. }
  38143. // Bounding info
  38144. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38145. return geometry;
  38146. };
  38147. /**
  38148. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38149. * @return a JSON representation of the current geometry data (without the vertices data)
  38150. */
  38151. Geometry.prototype.serialize = function () {
  38152. var serializationObject = {};
  38153. serializationObject.id = this.id;
  38154. serializationObject.updatable = this._updatable;
  38155. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38156. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38157. }
  38158. return serializationObject;
  38159. };
  38160. Geometry.prototype.toNumberArray = function (origin) {
  38161. if (Array.isArray(origin)) {
  38162. return origin;
  38163. }
  38164. else {
  38165. return Array.prototype.slice.call(origin);
  38166. }
  38167. };
  38168. /**
  38169. * Serialize all vertices data into a JSON oject
  38170. * @returns a JSON representation of the current geometry data
  38171. */
  38172. Geometry.prototype.serializeVerticeData = function () {
  38173. var serializationObject = this.serialize();
  38174. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38175. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38176. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38177. serializationObject.positions._updatable = true;
  38178. }
  38179. }
  38180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38181. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38182. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38183. serializationObject.normals._updatable = true;
  38184. }
  38185. }
  38186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38187. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38188. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38189. serializationObject.tangets._updatable = true;
  38190. }
  38191. }
  38192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38193. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38194. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38195. serializationObject.uvs._updatable = true;
  38196. }
  38197. }
  38198. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38199. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38200. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38201. serializationObject.uv2s._updatable = true;
  38202. }
  38203. }
  38204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38205. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38206. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38207. serializationObject.uv3s._updatable = true;
  38208. }
  38209. }
  38210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38211. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38212. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38213. serializationObject.uv4s._updatable = true;
  38214. }
  38215. }
  38216. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38217. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38218. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38219. serializationObject.uv5s._updatable = true;
  38220. }
  38221. }
  38222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38223. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38224. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38225. serializationObject.uv6s._updatable = true;
  38226. }
  38227. }
  38228. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38229. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38230. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38231. serializationObject.colors._updatable = true;
  38232. }
  38233. }
  38234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38235. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38236. serializationObject.matricesIndices._isExpanded = true;
  38237. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38238. serializationObject.matricesIndices._updatable = true;
  38239. }
  38240. }
  38241. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38242. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38243. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38244. serializationObject.matricesWeights._updatable = true;
  38245. }
  38246. }
  38247. serializationObject.indices = this.toNumberArray(this.getIndices());
  38248. return serializationObject;
  38249. };
  38250. // Statics
  38251. /**
  38252. * Extracts a clone of a mesh geometry
  38253. * @param mesh defines the source mesh
  38254. * @param id defines the unique ID of the new geometry object
  38255. * @returns the new geometry object
  38256. */
  38257. Geometry.ExtractFromMesh = function (mesh, id) {
  38258. var geometry = mesh._geometry;
  38259. if (!geometry) {
  38260. return null;
  38261. }
  38262. return geometry.copy(id);
  38263. };
  38264. /**
  38265. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38266. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38267. * Be aware Math.random() could cause collisions, but:
  38268. * "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"
  38269. * @returns a string containing a new GUID
  38270. */
  38271. Geometry.RandomId = function () {
  38272. return BABYLON.Tools.RandomId();
  38273. };
  38274. /** @ignore */
  38275. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38276. var scene = mesh.getScene();
  38277. // Geometry
  38278. var geometryId = parsedGeometry.geometryId;
  38279. if (geometryId) {
  38280. var geometry = scene.getGeometryByID(geometryId);
  38281. if (geometry) {
  38282. geometry.applyToMesh(mesh);
  38283. }
  38284. }
  38285. else if (parsedGeometry instanceof ArrayBuffer) {
  38286. var binaryInfo = mesh._binaryInfo;
  38287. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38288. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38289. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38290. }
  38291. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38292. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38293. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38294. }
  38295. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38296. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38297. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38298. }
  38299. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38300. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38301. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38302. }
  38303. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38304. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38305. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38306. }
  38307. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38308. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38309. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38310. }
  38311. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38312. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38313. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38314. }
  38315. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38316. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38317. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38318. }
  38319. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38320. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38321. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38322. }
  38323. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38324. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38325. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38326. }
  38327. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38328. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38329. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38330. }
  38331. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38332. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38333. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38334. }
  38335. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38336. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38337. mesh.setIndices(indicesData, null);
  38338. }
  38339. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38340. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38341. mesh.subMeshes = [];
  38342. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38343. var materialIndex = subMeshesData[(i * 5) + 0];
  38344. var verticesStart = subMeshesData[(i * 5) + 1];
  38345. var verticesCount = subMeshesData[(i * 5) + 2];
  38346. var indexStart = subMeshesData[(i * 5) + 3];
  38347. var indexCount = subMeshesData[(i * 5) + 4];
  38348. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38349. }
  38350. }
  38351. }
  38352. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38353. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38354. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38355. if (parsedGeometry.tangents) {
  38356. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38357. }
  38358. if (parsedGeometry.uvs) {
  38359. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38360. }
  38361. if (parsedGeometry.uvs2) {
  38362. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38363. }
  38364. if (parsedGeometry.uvs3) {
  38365. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38366. }
  38367. if (parsedGeometry.uvs4) {
  38368. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38369. }
  38370. if (parsedGeometry.uvs5) {
  38371. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38372. }
  38373. if (parsedGeometry.uvs6) {
  38374. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38375. }
  38376. if (parsedGeometry.colors) {
  38377. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38378. }
  38379. if (parsedGeometry.matricesIndices) {
  38380. if (!parsedGeometry.matricesIndices._isExpanded) {
  38381. var floatIndices = [];
  38382. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38383. var matricesIndex = parsedGeometry.matricesIndices[i];
  38384. floatIndices.push(matricesIndex & 0x000000FF);
  38385. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38386. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38387. floatIndices.push(matricesIndex >> 24);
  38388. }
  38389. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38390. }
  38391. else {
  38392. delete parsedGeometry.matricesIndices._isExpanded;
  38393. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38394. }
  38395. }
  38396. if (parsedGeometry.matricesIndicesExtra) {
  38397. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38398. var floatIndices = [];
  38399. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38400. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38401. floatIndices.push(matricesIndex & 0x000000FF);
  38402. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38403. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38404. floatIndices.push(matricesIndex >> 24);
  38405. }
  38406. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38407. }
  38408. else {
  38409. delete parsedGeometry.matricesIndices._isExpanded;
  38410. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38411. }
  38412. }
  38413. if (parsedGeometry.matricesWeights) {
  38414. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38416. }
  38417. if (parsedGeometry.matricesWeightsExtra) {
  38418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38419. }
  38420. mesh.setIndices(parsedGeometry.indices, null);
  38421. }
  38422. // SubMeshes
  38423. if (parsedGeometry.subMeshes) {
  38424. mesh.subMeshes = [];
  38425. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38426. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38427. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38428. }
  38429. }
  38430. // Flat shading
  38431. if (mesh._shouldGenerateFlatShading) {
  38432. mesh.convertToFlatShadedMesh();
  38433. delete mesh._shouldGenerateFlatShading;
  38434. }
  38435. // Update
  38436. mesh.computeWorldMatrix(true);
  38437. // Octree
  38438. var sceneOctree = scene.selectionOctree;
  38439. if (sceneOctree !== undefined && sceneOctree !== null) {
  38440. sceneOctree.addMesh(mesh);
  38441. }
  38442. };
  38443. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38444. var epsilon = 1e-3;
  38445. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38446. return;
  38447. }
  38448. var noInfluenceBoneIndex = 0.0;
  38449. if (parsedGeometry.skeletonId > -1) {
  38450. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  38451. if (!skeleton) {
  38452. return;
  38453. }
  38454. noInfluenceBoneIndex = skeleton.bones.length;
  38455. }
  38456. else {
  38457. return;
  38458. }
  38459. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  38460. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38461. var matricesWeights = parsedGeometry.matricesWeights;
  38462. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  38463. var influencers = parsedGeometry.numBoneInfluencer;
  38464. var size = matricesWeights.length;
  38465. for (var i = 0; i < size; i += 4) {
  38466. var weight = 0.0;
  38467. var firstZeroWeight = -1;
  38468. for (var j = 0; j < 4; j++) {
  38469. var w = matricesWeights[i + j];
  38470. weight += w;
  38471. if (w < epsilon && firstZeroWeight < 0) {
  38472. firstZeroWeight = j;
  38473. }
  38474. }
  38475. if (matricesWeightsExtra) {
  38476. for (var j = 0; j < 4; j++) {
  38477. var w = matricesWeightsExtra[i + j];
  38478. weight += w;
  38479. if (w < epsilon && firstZeroWeight < 0) {
  38480. firstZeroWeight = j + 4;
  38481. }
  38482. }
  38483. }
  38484. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  38485. firstZeroWeight = influencers - 1;
  38486. }
  38487. if (weight > epsilon) {
  38488. var mweight = 1.0 / weight;
  38489. for (var j = 0; j < 4; j++) {
  38490. matricesWeights[i + j] *= mweight;
  38491. }
  38492. if (matricesWeightsExtra) {
  38493. for (var j = 0; j < 4; j++) {
  38494. matricesWeightsExtra[i + j] *= mweight;
  38495. }
  38496. }
  38497. }
  38498. else {
  38499. if (firstZeroWeight >= 4) {
  38500. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  38501. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  38502. }
  38503. else {
  38504. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  38505. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  38506. }
  38507. }
  38508. }
  38509. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  38510. if (parsedGeometry.matricesWeightsExtra) {
  38511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  38512. }
  38513. };
  38514. /**
  38515. * Create a new geometry from persisted data (Using .babylon file format)
  38516. * @param parsedVertexData defines the persisted data
  38517. * @param scene defines the hosting scene
  38518. * @param rootUrl defines the root url to use to load assets (like delayed data)
  38519. * @returns the new geometry object
  38520. */
  38521. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  38522. if (scene.getGeometryByID(parsedVertexData.id)) {
  38523. return null; // null since geometry could be something else than a box...
  38524. }
  38525. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  38526. if (BABYLON.Tags) {
  38527. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  38528. }
  38529. if (parsedVertexData.delayLoadingFile) {
  38530. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38531. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  38532. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  38533. geometry._delayInfo = [];
  38534. if (parsedVertexData.hasUVs) {
  38535. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  38536. }
  38537. if (parsedVertexData.hasUVs2) {
  38538. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  38539. }
  38540. if (parsedVertexData.hasUVs3) {
  38541. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  38542. }
  38543. if (parsedVertexData.hasUVs4) {
  38544. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38545. }
  38546. if (parsedVertexData.hasUVs5) {
  38547. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  38548. }
  38549. if (parsedVertexData.hasUVs6) {
  38550. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  38551. }
  38552. if (parsedVertexData.hasColors) {
  38553. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  38554. }
  38555. if (parsedVertexData.hasMatricesIndices) {
  38556. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38557. }
  38558. if (parsedVertexData.hasMatricesWeights) {
  38559. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38560. }
  38561. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  38562. }
  38563. else {
  38564. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  38565. }
  38566. scene.pushGeometry(geometry, true);
  38567. return geometry;
  38568. };
  38569. return Geometry;
  38570. }());
  38571. BABYLON.Geometry = Geometry;
  38572. // Primitives
  38573. /// Abstract class
  38574. /**
  38575. * Abstract class used to provide common services for all typed geometries
  38576. */
  38577. var _PrimitiveGeometry = /** @class */ (function (_super) {
  38578. __extends(_PrimitiveGeometry, _super);
  38579. /**
  38580. * Creates a new typed geometry
  38581. * @param id defines the unique ID of the geometry
  38582. * @param scene defines the hosting scene
  38583. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38584. * @param mesh defines the hosting mesh (can be null)
  38585. */
  38586. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  38587. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  38588. if (mesh === void 0) { mesh = null; }
  38589. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  38590. _this._canBeRegenerated = _canBeRegenerated;
  38591. _this._beingRegenerated = true;
  38592. _this.regenerate();
  38593. _this._beingRegenerated = false;
  38594. return _this;
  38595. }
  38596. /**
  38597. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  38598. * @returns true if the geometry can be regenerated
  38599. */
  38600. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  38601. return this._canBeRegenerated;
  38602. };
  38603. /**
  38604. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  38605. */
  38606. _PrimitiveGeometry.prototype.regenerate = function () {
  38607. if (!this._canBeRegenerated) {
  38608. return;
  38609. }
  38610. this._beingRegenerated = true;
  38611. this.setAllVerticesData(this._regenerateVertexData(), false);
  38612. this._beingRegenerated = false;
  38613. };
  38614. /**
  38615. * Clone the geometry
  38616. * @param id defines the unique ID of the new geometry
  38617. * @returns the new geometry
  38618. */
  38619. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  38620. return _super.prototype.copy.call(this, id);
  38621. };
  38622. // overrides
  38623. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38624. if (!this._beingRegenerated) {
  38625. return;
  38626. }
  38627. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  38628. };
  38629. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  38630. if (!this._beingRegenerated) {
  38631. return;
  38632. }
  38633. _super.prototype.setVerticesData.call(this, kind, data, false);
  38634. };
  38635. // to override
  38636. /** @ignore */
  38637. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  38638. throw new Error("Abstract method");
  38639. };
  38640. _PrimitiveGeometry.prototype.copy = function (id) {
  38641. throw new Error("Must be overriden in sub-classes.");
  38642. };
  38643. _PrimitiveGeometry.prototype.serialize = function () {
  38644. var serializationObject = _super.prototype.serialize.call(this);
  38645. serializationObject.canBeRegenerated = this.canBeRegenerated();
  38646. return serializationObject;
  38647. };
  38648. return _PrimitiveGeometry;
  38649. }(Geometry));
  38650. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  38651. /**
  38652. * Creates a ribbon geometry
  38653. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  38654. */
  38655. var RibbonGeometry = /** @class */ (function (_super) {
  38656. __extends(RibbonGeometry, _super);
  38657. /**
  38658. * Creates a ribbon geometry
  38659. * @param id defines the unique ID of the geometry
  38660. * @param scene defines the hosting scene
  38661. * @param pathArray defines the array of paths to use
  38662. * @param closeArray defines if the last path and the first path must be joined
  38663. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  38664. * @param offset defines the offset between points
  38665. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38666. * @param mesh defines the hosting mesh (can be null)
  38667. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38668. */
  38669. function RibbonGeometry(id, scene,
  38670. /**
  38671. * Defines the array of paths to use
  38672. */
  38673. pathArray,
  38674. /**
  38675. * Defines if the last and first points of each path in your pathArray must be joined
  38676. */
  38677. closeArray,
  38678. /**
  38679. * Defines if the last and first points of each path in your pathArray must be joined
  38680. */
  38681. closePath,
  38682. /**
  38683. * Defines the offset between points
  38684. */
  38685. offset, canBeRegenerated, mesh,
  38686. /**
  38687. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38688. */
  38689. side) {
  38690. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38691. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38692. _this.pathArray = pathArray;
  38693. _this.closeArray = closeArray;
  38694. _this.closePath = closePath;
  38695. _this.offset = offset;
  38696. _this.side = side;
  38697. return _this;
  38698. }
  38699. /** @ignore */
  38700. RibbonGeometry.prototype._regenerateVertexData = function () {
  38701. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  38702. };
  38703. RibbonGeometry.prototype.copy = function (id) {
  38704. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  38705. };
  38706. return RibbonGeometry;
  38707. }(_PrimitiveGeometry));
  38708. BABYLON.RibbonGeometry = RibbonGeometry;
  38709. /**
  38710. * Creates a box geometry
  38711. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  38712. */
  38713. var BoxGeometry = /** @class */ (function (_super) {
  38714. __extends(BoxGeometry, _super);
  38715. /**
  38716. * Creates a box geometry
  38717. * @param id defines the unique ID of the geometry
  38718. * @param scene defines the hosting scene
  38719. * @param size defines the zise of the box (width, height and depth are the same)
  38720. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38721. * @param mesh defines the hosting mesh (can be null)
  38722. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38723. */
  38724. function BoxGeometry(id, scene,
  38725. /**
  38726. * Defines the zise of the box (width, height and depth are the same)
  38727. */
  38728. size, canBeRegenerated, mesh,
  38729. /**
  38730. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38731. */
  38732. side) {
  38733. if (mesh === void 0) { mesh = null; }
  38734. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38735. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38736. _this.size = size;
  38737. _this.side = side;
  38738. return _this;
  38739. }
  38740. BoxGeometry.prototype._regenerateVertexData = function () {
  38741. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  38742. };
  38743. BoxGeometry.prototype.copy = function (id) {
  38744. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  38745. };
  38746. BoxGeometry.prototype.serialize = function () {
  38747. var serializationObject = _super.prototype.serialize.call(this);
  38748. serializationObject.size = this.size;
  38749. return serializationObject;
  38750. };
  38751. BoxGeometry.Parse = function (parsedBox, scene) {
  38752. if (scene.getGeometryByID(parsedBox.id)) {
  38753. return null; // null since geometry could be something else than a box...
  38754. }
  38755. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  38756. if (BABYLON.Tags) {
  38757. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  38758. }
  38759. scene.pushGeometry(box, true);
  38760. return box;
  38761. };
  38762. return BoxGeometry;
  38763. }(_PrimitiveGeometry));
  38764. BABYLON.BoxGeometry = BoxGeometry;
  38765. /**
  38766. * Creates a sphere geometry
  38767. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  38768. */
  38769. var SphereGeometry = /** @class */ (function (_super) {
  38770. __extends(SphereGeometry, _super);
  38771. /**
  38772. * Create a new sphere geometry
  38773. * @param id defines the unique ID of the geometry
  38774. * @param scene defines the hosting scene
  38775. * @param segments defines the number of segments to use to create the sphere
  38776. * @param diameter defines the diameter of the sphere
  38777. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38778. * @param mesh defines the hosting mesh (can be null)
  38779. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38780. */
  38781. function SphereGeometry(id, scene,
  38782. /**
  38783. * Defines the number of segments to use to create the sphere
  38784. */
  38785. segments,
  38786. /**
  38787. * Defines the diameter of the sphere
  38788. */
  38789. diameter, canBeRegenerated, mesh,
  38790. /**
  38791. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38792. */
  38793. side) {
  38794. if (mesh === void 0) { mesh = null; }
  38795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38797. _this.segments = segments;
  38798. _this.diameter = diameter;
  38799. _this.side = side;
  38800. return _this;
  38801. }
  38802. SphereGeometry.prototype._regenerateVertexData = function () {
  38803. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  38804. };
  38805. SphereGeometry.prototype.copy = function (id) {
  38806. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  38807. };
  38808. SphereGeometry.prototype.serialize = function () {
  38809. var serializationObject = _super.prototype.serialize.call(this);
  38810. serializationObject.segments = this.segments;
  38811. serializationObject.diameter = this.diameter;
  38812. return serializationObject;
  38813. };
  38814. SphereGeometry.Parse = function (parsedSphere, scene) {
  38815. if (scene.getGeometryByID(parsedSphere.id)) {
  38816. return null; // null since geometry could be something else than a sphere...
  38817. }
  38818. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  38819. if (BABYLON.Tags) {
  38820. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  38821. }
  38822. scene.pushGeometry(sphere, true);
  38823. return sphere;
  38824. };
  38825. return SphereGeometry;
  38826. }(_PrimitiveGeometry));
  38827. BABYLON.SphereGeometry = SphereGeometry;
  38828. /**
  38829. * Creates a disc geometry
  38830. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  38831. */
  38832. var DiscGeometry = /** @class */ (function (_super) {
  38833. __extends(DiscGeometry, _super);
  38834. /**
  38835. * Creates a new disc geometry
  38836. * @param id defines the unique ID of the geometry
  38837. * @param scene defines the hosting scene
  38838. * @param radius defines the radius of the disc
  38839. * @param tessellation defines the tesselation factor to apply to the disc
  38840. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38841. * @param mesh defines the hosting mesh (can be null)
  38842. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38843. */
  38844. function DiscGeometry(id, scene,
  38845. /**
  38846. * Defines the radius of the disc
  38847. */
  38848. radius,
  38849. /**
  38850. * Defines the tesselation factor to apply to the disc
  38851. */
  38852. tessellation, canBeRegenerated, mesh,
  38853. /**
  38854. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38855. */
  38856. side) {
  38857. if (mesh === void 0) { mesh = null; }
  38858. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38859. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38860. _this.radius = radius;
  38861. _this.tessellation = tessellation;
  38862. _this.side = side;
  38863. return _this;
  38864. }
  38865. DiscGeometry.prototype._regenerateVertexData = function () {
  38866. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  38867. };
  38868. DiscGeometry.prototype.copy = function (id) {
  38869. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  38870. };
  38871. return DiscGeometry;
  38872. }(_PrimitiveGeometry));
  38873. BABYLON.DiscGeometry = DiscGeometry;
  38874. /**
  38875. * Creates a new cylinder geometry
  38876. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  38877. */
  38878. var CylinderGeometry = /** @class */ (function (_super) {
  38879. __extends(CylinderGeometry, _super);
  38880. /**
  38881. * Creates a new cylinder geometry
  38882. * @param id defines the unique ID of the geometry
  38883. * @param scene defines the hosting scene
  38884. * @param height defines the height of the cylinder
  38885. * @param diameterTop defines the diameter of the cylinder's top cap
  38886. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  38887. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  38888. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  38889. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38890. * @param mesh defines the hosting mesh (can be null)
  38891. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38892. */
  38893. function CylinderGeometry(id, scene,
  38894. /**
  38895. * Defines the height of the cylinder
  38896. */
  38897. height,
  38898. /**
  38899. * Defines the diameter of the cylinder's top cap
  38900. */
  38901. diameterTop,
  38902. /**
  38903. * Defines the diameter of the cylinder's bottom cap
  38904. */
  38905. diameterBottom,
  38906. /**
  38907. * Defines the tessellation factor to apply to the cylinder
  38908. */
  38909. tessellation,
  38910. /**
  38911. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  38912. */
  38913. subdivisions, canBeRegenerated, mesh,
  38914. /**
  38915. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38916. */
  38917. side) {
  38918. if (subdivisions === void 0) { subdivisions = 1; }
  38919. if (mesh === void 0) { mesh = null; }
  38920. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38921. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38922. _this.height = height;
  38923. _this.diameterTop = diameterTop;
  38924. _this.diameterBottom = diameterBottom;
  38925. _this.tessellation = tessellation;
  38926. _this.subdivisions = subdivisions;
  38927. _this.side = side;
  38928. return _this;
  38929. }
  38930. CylinderGeometry.prototype._regenerateVertexData = function () {
  38931. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  38932. };
  38933. CylinderGeometry.prototype.copy = function (id) {
  38934. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  38935. };
  38936. CylinderGeometry.prototype.serialize = function () {
  38937. var serializationObject = _super.prototype.serialize.call(this);
  38938. serializationObject.height = this.height;
  38939. serializationObject.diameterTop = this.diameterTop;
  38940. serializationObject.diameterBottom = this.diameterBottom;
  38941. serializationObject.tessellation = this.tessellation;
  38942. return serializationObject;
  38943. };
  38944. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  38945. if (scene.getGeometryByID(parsedCylinder.id)) {
  38946. return null; // null since geometry could be something else than a cylinder...
  38947. }
  38948. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  38949. if (BABYLON.Tags) {
  38950. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  38951. }
  38952. scene.pushGeometry(cylinder, true);
  38953. return cylinder;
  38954. };
  38955. return CylinderGeometry;
  38956. }(_PrimitiveGeometry));
  38957. BABYLON.CylinderGeometry = CylinderGeometry;
  38958. /**
  38959. * Creates a new torus geometry
  38960. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  38961. */
  38962. var TorusGeometry = /** @class */ (function (_super) {
  38963. __extends(TorusGeometry, _super);
  38964. /**
  38965. * Creates a new torus geometry
  38966. * @param id defines the unique ID of the geometry
  38967. * @param scene defines the hosting scene
  38968. * @param diameter defines the diameter of the torus
  38969. * @param thickness defines the thickness of the torus (ie. internal diameter)
  38970. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  38971. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38972. * @param mesh defines the hosting mesh (can be null)
  38973. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38974. */
  38975. function TorusGeometry(id, scene,
  38976. /**
  38977. * Defines the diameter of the torus
  38978. */
  38979. diameter,
  38980. /**
  38981. * Defines the thickness of the torus (ie. internal diameter)
  38982. */
  38983. thickness,
  38984. /**
  38985. * Defines the tesselation factor to apply to the torus
  38986. */
  38987. tessellation, canBeRegenerated, mesh,
  38988. /**
  38989. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38990. */
  38991. side) {
  38992. if (mesh === void 0) { mesh = null; }
  38993. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38994. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38995. _this.diameter = diameter;
  38996. _this.thickness = thickness;
  38997. _this.tessellation = tessellation;
  38998. _this.side = side;
  38999. return _this;
  39000. }
  39001. TorusGeometry.prototype._regenerateVertexData = function () {
  39002. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39003. };
  39004. TorusGeometry.prototype.copy = function (id) {
  39005. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39006. };
  39007. TorusGeometry.prototype.serialize = function () {
  39008. var serializationObject = _super.prototype.serialize.call(this);
  39009. serializationObject.diameter = this.diameter;
  39010. serializationObject.thickness = this.thickness;
  39011. serializationObject.tessellation = this.tessellation;
  39012. return serializationObject;
  39013. };
  39014. TorusGeometry.Parse = function (parsedTorus, scene) {
  39015. if (scene.getGeometryByID(parsedTorus.id)) {
  39016. return null; // null since geometry could be something else than a torus...
  39017. }
  39018. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39019. if (BABYLON.Tags) {
  39020. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39021. }
  39022. scene.pushGeometry(torus, true);
  39023. return torus;
  39024. };
  39025. return TorusGeometry;
  39026. }(_PrimitiveGeometry));
  39027. BABYLON.TorusGeometry = TorusGeometry;
  39028. /**
  39029. * Creates a new ground geometry
  39030. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39031. */
  39032. var GroundGeometry = /** @class */ (function (_super) {
  39033. __extends(GroundGeometry, _super);
  39034. /**
  39035. * Creates a new ground geometry
  39036. * @param id defines the unique ID of the geometry
  39037. * @param scene defines the hosting scene
  39038. * @param width defines the width of the ground
  39039. * @param height defines the height of the ground
  39040. * @param subdivisions defines the subdivisions to apply to the ground
  39041. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39042. * @param mesh defines the hosting mesh (can be null)
  39043. */
  39044. function GroundGeometry(id, scene,
  39045. /**
  39046. * Defines the width of the ground
  39047. */
  39048. width,
  39049. /**
  39050. * Defines the height of the ground
  39051. */
  39052. height,
  39053. /**
  39054. * Defines the subdivisions to apply to the ground
  39055. */
  39056. subdivisions, canBeRegenerated, mesh) {
  39057. if (mesh === void 0) { mesh = null; }
  39058. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39059. _this.width = width;
  39060. _this.height = height;
  39061. _this.subdivisions = subdivisions;
  39062. return _this;
  39063. }
  39064. GroundGeometry.prototype._regenerateVertexData = function () {
  39065. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39066. };
  39067. GroundGeometry.prototype.copy = function (id) {
  39068. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39069. };
  39070. GroundGeometry.prototype.serialize = function () {
  39071. var serializationObject = _super.prototype.serialize.call(this);
  39072. serializationObject.width = this.width;
  39073. serializationObject.height = this.height;
  39074. serializationObject.subdivisions = this.subdivisions;
  39075. return serializationObject;
  39076. };
  39077. GroundGeometry.Parse = function (parsedGround, scene) {
  39078. if (scene.getGeometryByID(parsedGround.id)) {
  39079. return null; // null since geometry could be something else than a ground...
  39080. }
  39081. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39082. if (BABYLON.Tags) {
  39083. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39084. }
  39085. scene.pushGeometry(ground, true);
  39086. return ground;
  39087. };
  39088. return GroundGeometry;
  39089. }(_PrimitiveGeometry));
  39090. BABYLON.GroundGeometry = GroundGeometry;
  39091. /**
  39092. * Creates a tiled ground geometry
  39093. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39094. */
  39095. var TiledGroundGeometry = /** @class */ (function (_super) {
  39096. __extends(TiledGroundGeometry, _super);
  39097. /**
  39098. * Creates a tiled ground geometry
  39099. * @param id defines the unique ID of the geometry
  39100. * @param scene defines the hosting scene
  39101. * @param xmin defines the minimum value on X axis
  39102. * @param zmin defines the minimum value on Z axis
  39103. * @param xmax defines the maximum value on X axis
  39104. * @param zmax defines the maximum value on Z axis
  39105. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39106. * @param precision defines the precision to use when computing the tiles
  39107. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39108. * @param mesh defines the hosting mesh (can be null)
  39109. */
  39110. function TiledGroundGeometry(id, scene,
  39111. /**
  39112. * Defines the minimum value on X axis
  39113. */
  39114. xmin,
  39115. /**
  39116. * Defines the minimum value on Z axis
  39117. */
  39118. zmin,
  39119. /**
  39120. * Defines the maximum value on X axis
  39121. */
  39122. xmax,
  39123. /**
  39124. * Defines the maximum value on Z axis
  39125. */
  39126. zmax,
  39127. /**
  39128. * Defines the subdivisions to apply to the ground
  39129. */
  39130. subdivisions,
  39131. /**
  39132. * Defines the precision to use when computing the tiles
  39133. */
  39134. precision, canBeRegenerated, mesh) {
  39135. if (mesh === void 0) { mesh = null; }
  39136. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39137. _this.xmin = xmin;
  39138. _this.zmin = zmin;
  39139. _this.xmax = xmax;
  39140. _this.zmax = zmax;
  39141. _this.subdivisions = subdivisions;
  39142. _this.precision = precision;
  39143. return _this;
  39144. }
  39145. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39146. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39147. };
  39148. TiledGroundGeometry.prototype.copy = function (id) {
  39149. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39150. };
  39151. return TiledGroundGeometry;
  39152. }(_PrimitiveGeometry));
  39153. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39154. /**
  39155. * Creates a plane geometry
  39156. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39157. */
  39158. var PlaneGeometry = /** @class */ (function (_super) {
  39159. __extends(PlaneGeometry, _super);
  39160. /**
  39161. * Creates a plane geometry
  39162. * @param id defines the unique ID of the geometry
  39163. * @param scene defines the hosting scene
  39164. * @param size defines the size of the plane (width === height)
  39165. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39166. * @param mesh defines the hosting mesh (can be null)
  39167. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39168. */
  39169. function PlaneGeometry(id, scene,
  39170. /**
  39171. * Defines the size of the plane (width === height)
  39172. */
  39173. size, canBeRegenerated, mesh,
  39174. /**
  39175. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39176. */
  39177. side) {
  39178. if (mesh === void 0) { mesh = null; }
  39179. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39180. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39181. _this.size = size;
  39182. _this.side = side;
  39183. return _this;
  39184. }
  39185. PlaneGeometry.prototype._regenerateVertexData = function () {
  39186. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39187. };
  39188. PlaneGeometry.prototype.copy = function (id) {
  39189. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39190. };
  39191. PlaneGeometry.prototype.serialize = function () {
  39192. var serializationObject = _super.prototype.serialize.call(this);
  39193. serializationObject.size = this.size;
  39194. return serializationObject;
  39195. };
  39196. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39197. if (scene.getGeometryByID(parsedPlane.id)) {
  39198. return null; // null since geometry could be something else than a ground...
  39199. }
  39200. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39201. if (BABYLON.Tags) {
  39202. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39203. }
  39204. scene.pushGeometry(plane, true);
  39205. return plane;
  39206. };
  39207. return PlaneGeometry;
  39208. }(_PrimitiveGeometry));
  39209. BABYLON.PlaneGeometry = PlaneGeometry;
  39210. /**
  39211. * Creates a torus knot geometry
  39212. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39213. */
  39214. var TorusKnotGeometry = /** @class */ (function (_super) {
  39215. __extends(TorusKnotGeometry, _super);
  39216. /**
  39217. * Creates a torus knot geometry
  39218. * @param id defines the unique ID of the geometry
  39219. * @param scene defines the hosting scene
  39220. * @param radius defines the radius of the torus knot
  39221. * @param tube defines the thickness of the torus knot tube
  39222. * @param radialSegments defines the number of radial segments
  39223. * @param tubularSegments defines the number of tubular segments
  39224. * @param p defines the first number of windings
  39225. * @param q defines the second number of windings
  39226. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39227. * @param mesh defines the hosting mesh (can be null)
  39228. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39229. */
  39230. function TorusKnotGeometry(id, scene,
  39231. /**
  39232. * Defines the radius of the torus knot
  39233. */
  39234. radius,
  39235. /**
  39236. * Defines the thickness of the torus knot tube
  39237. */
  39238. tube,
  39239. /**
  39240. * Defines the number of radial segments
  39241. */
  39242. radialSegments,
  39243. /**
  39244. * Defines the number of tubular segments
  39245. */
  39246. tubularSegments,
  39247. /**
  39248. * Defines the first number of windings
  39249. */
  39250. p,
  39251. /**
  39252. * Defines the second number of windings
  39253. */
  39254. q, canBeRegenerated, mesh,
  39255. /**
  39256. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39257. */
  39258. side) {
  39259. if (mesh === void 0) { mesh = null; }
  39260. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39261. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39262. _this.radius = radius;
  39263. _this.tube = tube;
  39264. _this.radialSegments = radialSegments;
  39265. _this.tubularSegments = tubularSegments;
  39266. _this.p = p;
  39267. _this.q = q;
  39268. _this.side = side;
  39269. return _this;
  39270. }
  39271. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39272. 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 });
  39273. };
  39274. TorusKnotGeometry.prototype.copy = function (id) {
  39275. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39276. };
  39277. TorusKnotGeometry.prototype.serialize = function () {
  39278. var serializationObject = _super.prototype.serialize.call(this);
  39279. serializationObject.radius = this.radius;
  39280. serializationObject.tube = this.tube;
  39281. serializationObject.radialSegments = this.radialSegments;
  39282. serializationObject.tubularSegments = this.tubularSegments;
  39283. serializationObject.p = this.p;
  39284. serializationObject.q = this.q;
  39285. return serializationObject;
  39286. };
  39287. ;
  39288. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39289. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39290. return null; // null since geometry could be something else than a ground...
  39291. }
  39292. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39293. if (BABYLON.Tags) {
  39294. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39295. }
  39296. scene.pushGeometry(torusKnot, true);
  39297. return torusKnot;
  39298. };
  39299. return TorusKnotGeometry;
  39300. }(_PrimitiveGeometry));
  39301. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39302. //}
  39303. })(BABYLON || (BABYLON = {}));
  39304. //# sourceMappingURL=babylon.geometry.js.map
  39305. "use strict";
  39306. var BABYLON;
  39307. (function (BABYLON) {
  39308. /**
  39309. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39310. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39311. */
  39312. var PostProcessManager = /** @class */ (function () {
  39313. /**
  39314. * Creates a new instance PostProcess
  39315. * @param scene The scene that the post process is associated with.
  39316. */
  39317. function PostProcessManager(scene) {
  39318. this._vertexBuffers = {};
  39319. this._scene = scene;
  39320. }
  39321. PostProcessManager.prototype._prepareBuffers = function () {
  39322. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39323. return;
  39324. }
  39325. // VBO
  39326. var vertices = [];
  39327. vertices.push(1, 1);
  39328. vertices.push(-1, 1);
  39329. vertices.push(-1, -1);
  39330. vertices.push(1, -1);
  39331. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39332. this._buildIndexBuffer();
  39333. };
  39334. PostProcessManager.prototype._buildIndexBuffer = function () {
  39335. // Indices
  39336. var indices = [];
  39337. indices.push(0);
  39338. indices.push(1);
  39339. indices.push(2);
  39340. indices.push(0);
  39341. indices.push(2);
  39342. indices.push(3);
  39343. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39344. };
  39345. /**
  39346. * Rebuilds the vertex buffers of the manager.
  39347. */
  39348. PostProcessManager.prototype._rebuild = function () {
  39349. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39350. if (!vb) {
  39351. return;
  39352. }
  39353. vb._rebuild();
  39354. this._buildIndexBuffer();
  39355. };
  39356. // Methods
  39357. /**
  39358. * Prepares a frame to be run through a post process.
  39359. * @param sourceTexture The input texture to the post procesess. (default: null)
  39360. * @param postProcesses An array of post processes to be run. (default: null)
  39361. * @returns True if the post processes were able to be run.
  39362. */
  39363. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39364. if (sourceTexture === void 0) { sourceTexture = null; }
  39365. if (postProcesses === void 0) { postProcesses = null; }
  39366. var camera = this._scene.activeCamera;
  39367. if (!camera) {
  39368. return false;
  39369. }
  39370. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39371. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39372. return false;
  39373. }
  39374. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39375. return true;
  39376. };
  39377. /**
  39378. * Manually render a set of post processes to a texture.
  39379. * @param postProcesses An array of post processes to be run.
  39380. * @param targetTexture The target texture to render to.
  39381. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39382. */
  39383. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39384. if (targetTexture === void 0) { targetTexture = null; }
  39385. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39386. var engine = this._scene.getEngine();
  39387. for (var index = 0; index < postProcesses.length; index++) {
  39388. if (index < postProcesses.length - 1) {
  39389. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39390. }
  39391. else {
  39392. if (targetTexture) {
  39393. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39394. }
  39395. else {
  39396. engine.restoreDefaultFramebuffer();
  39397. }
  39398. }
  39399. var pp = postProcesses[index];
  39400. var effect = pp.apply();
  39401. if (effect) {
  39402. pp.onBeforeRenderObservable.notifyObservers(effect);
  39403. // VBOs
  39404. this._prepareBuffers();
  39405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39406. // Draw order
  39407. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39408. pp.onAfterRenderObservable.notifyObservers(effect);
  39409. }
  39410. }
  39411. // Restore depth buffer
  39412. engine.setDepthBuffer(true);
  39413. engine.setDepthWrite(true);
  39414. };
  39415. /**
  39416. * Finalize the result of the output of the postprocesses.
  39417. * @param doNotPresent If true the result will not be displayed to the screen.
  39418. * @param targetTexture The target texture to render to.
  39419. * @param faceIndex The index of the face to bind the target texture to.
  39420. * @param postProcesses The array of post processes to render.
  39421. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39422. */
  39423. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39424. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39425. var camera = this._scene.activeCamera;
  39426. if (!camera) {
  39427. return;
  39428. }
  39429. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39430. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39431. return;
  39432. }
  39433. var engine = this._scene.getEngine();
  39434. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39435. var pp = postProcesses[index];
  39436. if (index < len - 1) {
  39437. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39438. }
  39439. else {
  39440. if (targetTexture) {
  39441. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39442. pp._outputTexture = targetTexture;
  39443. }
  39444. else {
  39445. engine.restoreDefaultFramebuffer();
  39446. pp._outputTexture = null;
  39447. }
  39448. }
  39449. if (doNotPresent) {
  39450. break;
  39451. }
  39452. var effect = pp.apply();
  39453. if (effect) {
  39454. pp.onBeforeRenderObservable.notifyObservers(effect);
  39455. // VBOs
  39456. this._prepareBuffers();
  39457. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39458. // Draw order
  39459. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39460. pp.onAfterRenderObservable.notifyObservers(effect);
  39461. }
  39462. }
  39463. // Restore states
  39464. engine.setDepthBuffer(true);
  39465. engine.setDepthWrite(true);
  39466. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39467. };
  39468. /**
  39469. * Disposes of the post process manager.
  39470. */
  39471. PostProcessManager.prototype.dispose = function () {
  39472. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39473. if (buffer) {
  39474. buffer.dispose();
  39475. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39476. }
  39477. if (this._indexBuffer) {
  39478. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39479. this._indexBuffer = null;
  39480. }
  39481. };
  39482. return PostProcessManager;
  39483. }());
  39484. BABYLON.PostProcessManager = PostProcessManager;
  39485. })(BABYLON || (BABYLON = {}));
  39486. //# sourceMappingURL=babylon.postProcessManager.js.map
  39487. "use strict";
  39488. var BABYLON;
  39489. (function (BABYLON) {
  39490. /**
  39491. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  39492. */
  39493. var PerformanceMonitor = /** @class */ (function () {
  39494. /**
  39495. * constructor
  39496. * @param frameSampleSize The number of samples required to saturate the sliding window
  39497. */
  39498. function PerformanceMonitor(frameSampleSize) {
  39499. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  39500. this._enabled = true;
  39501. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  39502. }
  39503. /**
  39504. * Samples current frame
  39505. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  39506. */
  39507. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  39508. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  39509. if (!this._enabled)
  39510. return;
  39511. if (this._lastFrameTimeMs != null) {
  39512. var dt = timeMs - this._lastFrameTimeMs;
  39513. this._rollingFrameTime.add(dt);
  39514. }
  39515. this._lastFrameTimeMs = timeMs;
  39516. };
  39517. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  39518. /**
  39519. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39520. * @return Average frame time in milliseconds
  39521. */
  39522. get: function () {
  39523. return this._rollingFrameTime.average;
  39524. },
  39525. enumerable: true,
  39526. configurable: true
  39527. });
  39528. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  39529. /**
  39530. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39531. * @return Frame time variance in milliseconds squared
  39532. */
  39533. get: function () {
  39534. return this._rollingFrameTime.variance;
  39535. },
  39536. enumerable: true,
  39537. configurable: true
  39538. });
  39539. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  39540. /**
  39541. * Returns the frame time of the most recent frame
  39542. * @return Frame time in milliseconds
  39543. */
  39544. get: function () {
  39545. return this._rollingFrameTime.history(0);
  39546. },
  39547. enumerable: true,
  39548. configurable: true
  39549. });
  39550. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  39551. /**
  39552. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  39553. * @return Framerate in frames per second
  39554. */
  39555. get: function () {
  39556. return 1000.0 / this._rollingFrameTime.average;
  39557. },
  39558. enumerable: true,
  39559. configurable: true
  39560. });
  39561. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  39562. /**
  39563. * Returns the average framerate in frames per second using the most recent frame time
  39564. * @return Framerate in frames per second
  39565. */
  39566. get: function () {
  39567. var history = this._rollingFrameTime.history(0);
  39568. if (history === 0) {
  39569. return 0;
  39570. }
  39571. return 1000.0 / history;
  39572. },
  39573. enumerable: true,
  39574. configurable: true
  39575. });
  39576. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  39577. /**
  39578. * Returns true if enough samples have been taken to completely fill the sliding window
  39579. * @return true if saturated
  39580. */
  39581. get: function () {
  39582. return this._rollingFrameTime.isSaturated();
  39583. },
  39584. enumerable: true,
  39585. configurable: true
  39586. });
  39587. /**
  39588. * Enables contributions to the sliding window sample set
  39589. */
  39590. PerformanceMonitor.prototype.enable = function () {
  39591. this._enabled = true;
  39592. };
  39593. /**
  39594. * Disables contributions to the sliding window sample set
  39595. * Samples will not be interpolated over the disabled period
  39596. */
  39597. PerformanceMonitor.prototype.disable = function () {
  39598. this._enabled = false;
  39599. //clear last sample to avoid interpolating over the disabled period when next enabled
  39600. this._lastFrameTimeMs = null;
  39601. };
  39602. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  39603. /**
  39604. * Returns true if sampling is enabled
  39605. * @return true if enabled
  39606. */
  39607. get: function () {
  39608. return this._enabled;
  39609. },
  39610. enumerable: true,
  39611. configurable: true
  39612. });
  39613. /**
  39614. * Resets performance monitor
  39615. */
  39616. PerformanceMonitor.prototype.reset = function () {
  39617. //clear last sample to avoid interpolating over the disabled period when next enabled
  39618. this._lastFrameTimeMs = null;
  39619. //wipe record
  39620. this._rollingFrameTime.reset();
  39621. };
  39622. return PerformanceMonitor;
  39623. }());
  39624. BABYLON.PerformanceMonitor = PerformanceMonitor;
  39625. /**
  39626. * RollingAverage
  39627. *
  39628. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  39629. */
  39630. var RollingAverage = /** @class */ (function () {
  39631. /**
  39632. * constructor
  39633. * @param length The number of samples required to saturate the sliding window
  39634. */
  39635. function RollingAverage(length) {
  39636. this._samples = new Array(length);
  39637. this.reset();
  39638. }
  39639. /**
  39640. * Adds a sample to the sample set
  39641. * @param v The sample value
  39642. */
  39643. RollingAverage.prototype.add = function (v) {
  39644. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  39645. var delta;
  39646. //we need to check if we've already wrapped round
  39647. if (this.isSaturated()) {
  39648. //remove bottom of stack from mean
  39649. var bottomValue = this._samples[this._pos];
  39650. delta = bottomValue - this.average;
  39651. this.average -= delta / (this._sampleCount - 1);
  39652. this._m2 -= delta * (bottomValue - this.average);
  39653. }
  39654. else {
  39655. this._sampleCount++;
  39656. }
  39657. //add new value to mean
  39658. delta = v - this.average;
  39659. this.average += delta / (this._sampleCount);
  39660. this._m2 += delta * (v - this.average);
  39661. //set the new variance
  39662. this.variance = this._m2 / (this._sampleCount - 1);
  39663. this._samples[this._pos] = v;
  39664. this._pos++;
  39665. this._pos %= this._samples.length; //positive wrap around
  39666. };
  39667. /**
  39668. * Returns previously added values or null if outside of history or outside the sliding window domain
  39669. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  39670. * @return Value previously recorded with add() or null if outside of range
  39671. */
  39672. RollingAverage.prototype.history = function (i) {
  39673. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  39674. return 0;
  39675. }
  39676. var i0 = this._wrapPosition(this._pos - 1.0);
  39677. return this._samples[this._wrapPosition(i0 - i)];
  39678. };
  39679. /**
  39680. * Returns true if enough samples have been taken to completely fill the sliding window
  39681. * @return true if sample-set saturated
  39682. */
  39683. RollingAverage.prototype.isSaturated = function () {
  39684. return this._sampleCount >= this._samples.length;
  39685. };
  39686. /**
  39687. * Resets the rolling average (equivalent to 0 samples taken so far)
  39688. */
  39689. RollingAverage.prototype.reset = function () {
  39690. this.average = 0;
  39691. this.variance = 0;
  39692. this._sampleCount = 0;
  39693. this._pos = 0;
  39694. this._m2 = 0;
  39695. };
  39696. /**
  39697. * Wraps a value around the sample range boundaries
  39698. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  39699. * @return Wrapped position in sample range
  39700. */
  39701. RollingAverage.prototype._wrapPosition = function (i) {
  39702. var max = this._samples.length;
  39703. return ((i % max) + max) % max;
  39704. };
  39705. return RollingAverage;
  39706. }());
  39707. BABYLON.RollingAverage = RollingAverage;
  39708. })(BABYLON || (BABYLON = {}));
  39709. //# sourceMappingURL=babylon.performanceMonitor.js.map
  39710. "use strict";
  39711. var BABYLON;
  39712. (function (BABYLON) {
  39713. /**
  39714. * This groups together the common properties used for image processing either in direct forward pass
  39715. * or through post processing effect depending on the use of the image processing pipeline in your scene
  39716. * or not.
  39717. */
  39718. var ImageProcessingConfiguration = /** @class */ (function () {
  39719. function ImageProcessingConfiguration() {
  39720. /**
  39721. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  39722. */
  39723. this.colorCurves = new BABYLON.ColorCurves();
  39724. this._colorCurvesEnabled = false;
  39725. this._colorGradingEnabled = false;
  39726. this._colorGradingWithGreenDepth = true;
  39727. this._colorGradingBGR = true;
  39728. this._exposure = 1.0;
  39729. this._toneMappingEnabled = false;
  39730. this._contrast = 1.0;
  39731. /**
  39732. * Vignette stretch size.
  39733. */
  39734. this.vignetteStretch = 0;
  39735. /**
  39736. * Vignette centre X Offset.
  39737. */
  39738. this.vignetteCentreX = 0;
  39739. /**
  39740. * Vignette centre Y Offset.
  39741. */
  39742. this.vignetteCentreY = 0;
  39743. /**
  39744. * Vignette weight or intensity of the vignette effect.
  39745. */
  39746. this.vignetteWeight = 1.5;
  39747. /**
  39748. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  39749. * if vignetteEnabled is set to true.
  39750. */
  39751. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  39752. /**
  39753. * Camera field of view used by the Vignette effect.
  39754. */
  39755. this.vignetteCameraFov = 0.5;
  39756. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  39757. this._vignetteEnabled = false;
  39758. this._applyByPostProcess = false;
  39759. this._isEnabled = true;
  39760. /**
  39761. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  39762. */
  39763. this.onUpdateParameters = new BABYLON.Observable();
  39764. }
  39765. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  39766. /**
  39767. * Gets wether the color curves effect is enabled.
  39768. */
  39769. get: function () {
  39770. return this._colorCurvesEnabled;
  39771. },
  39772. /**
  39773. * Sets wether the color curves effect is enabled.
  39774. */
  39775. set: function (value) {
  39776. if (this._colorCurvesEnabled === value) {
  39777. return;
  39778. }
  39779. this._colorCurvesEnabled = value;
  39780. this._updateParameters();
  39781. },
  39782. enumerable: true,
  39783. configurable: true
  39784. });
  39785. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  39786. /**
  39787. * Gets wether the color grading effect is enabled.
  39788. */
  39789. get: function () {
  39790. return this._colorGradingEnabled;
  39791. },
  39792. /**
  39793. * Sets wether the color grading effect is enabled.
  39794. */
  39795. set: function (value) {
  39796. if (this._colorGradingEnabled === value) {
  39797. return;
  39798. }
  39799. this._colorGradingEnabled = value;
  39800. this._updateParameters();
  39801. },
  39802. enumerable: true,
  39803. configurable: true
  39804. });
  39805. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  39806. /**
  39807. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  39808. */
  39809. get: function () {
  39810. return this._colorGradingWithGreenDepth;
  39811. },
  39812. /**
  39813. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  39814. */
  39815. set: function (value) {
  39816. if (this._colorGradingWithGreenDepth === value) {
  39817. return;
  39818. }
  39819. this._colorGradingWithGreenDepth = value;
  39820. this._updateParameters();
  39821. },
  39822. enumerable: true,
  39823. configurable: true
  39824. });
  39825. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  39826. /**
  39827. * Gets wether the color grading texture contains BGR values.
  39828. */
  39829. get: function () {
  39830. return this._colorGradingBGR;
  39831. },
  39832. /**
  39833. * Sets wether the color grading texture contains BGR values.
  39834. */
  39835. set: function (value) {
  39836. if (this._colorGradingBGR === value) {
  39837. return;
  39838. }
  39839. this._colorGradingBGR = value;
  39840. this._updateParameters();
  39841. },
  39842. enumerable: true,
  39843. configurable: true
  39844. });
  39845. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  39846. /**
  39847. * Gets the Exposure used in the effect.
  39848. */
  39849. get: function () {
  39850. return this._exposure;
  39851. },
  39852. /**
  39853. * Sets the Exposure used in the effect.
  39854. */
  39855. set: function (value) {
  39856. if (this._exposure === value) {
  39857. return;
  39858. }
  39859. this._exposure = value;
  39860. this._updateParameters();
  39861. },
  39862. enumerable: true,
  39863. configurable: true
  39864. });
  39865. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  39866. /**
  39867. * Gets wether the tone mapping effect is enabled.
  39868. */
  39869. get: function () {
  39870. return this._toneMappingEnabled;
  39871. },
  39872. /**
  39873. * Sets wether the tone mapping effect is enabled.
  39874. */
  39875. set: function (value) {
  39876. if (this._toneMappingEnabled === value) {
  39877. return;
  39878. }
  39879. this._toneMappingEnabled = value;
  39880. this._updateParameters();
  39881. },
  39882. enumerable: true,
  39883. configurable: true
  39884. });
  39885. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  39886. /**
  39887. * Gets the contrast used in the effect.
  39888. */
  39889. get: function () {
  39890. return this._contrast;
  39891. },
  39892. /**
  39893. * Sets the contrast used in the effect.
  39894. */
  39895. set: function (value) {
  39896. if (this._contrast === value) {
  39897. return;
  39898. }
  39899. this._contrast = value;
  39900. this._updateParameters();
  39901. },
  39902. enumerable: true,
  39903. configurable: true
  39904. });
  39905. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  39906. /**
  39907. * Gets the vignette blend mode allowing different kind of effect.
  39908. */
  39909. get: function () {
  39910. return this._vignetteBlendMode;
  39911. },
  39912. /**
  39913. * Sets the vignette blend mode allowing different kind of effect.
  39914. */
  39915. set: function (value) {
  39916. if (this._vignetteBlendMode === value) {
  39917. return;
  39918. }
  39919. this._vignetteBlendMode = value;
  39920. this._updateParameters();
  39921. },
  39922. enumerable: true,
  39923. configurable: true
  39924. });
  39925. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  39926. /**
  39927. * Gets wether the vignette effect is enabled.
  39928. */
  39929. get: function () {
  39930. return this._vignetteEnabled;
  39931. },
  39932. /**
  39933. * Sets wether the vignette effect is enabled.
  39934. */
  39935. set: function (value) {
  39936. if (this._vignetteEnabled === value) {
  39937. return;
  39938. }
  39939. this._vignetteEnabled = value;
  39940. this._updateParameters();
  39941. },
  39942. enumerable: true,
  39943. configurable: true
  39944. });
  39945. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  39946. /**
  39947. * Gets wether the image processing is applied through a post process or not.
  39948. */
  39949. get: function () {
  39950. return this._applyByPostProcess;
  39951. },
  39952. /**
  39953. * Sets wether the image processing is applied through a post process or not.
  39954. */
  39955. set: function (value) {
  39956. if (this._applyByPostProcess === value) {
  39957. return;
  39958. }
  39959. this._applyByPostProcess = value;
  39960. this._updateParameters();
  39961. },
  39962. enumerable: true,
  39963. configurable: true
  39964. });
  39965. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  39966. /**
  39967. * Gets wether the image processing is enabled or not.
  39968. */
  39969. get: function () {
  39970. return this._isEnabled;
  39971. },
  39972. /**
  39973. * Sets wether the image processing is enabled or not.
  39974. */
  39975. set: function (value) {
  39976. if (this._isEnabled === value) {
  39977. return;
  39978. }
  39979. this._isEnabled = value;
  39980. this._updateParameters();
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. /**
  39986. * Method called each time the image processing information changes requires to recompile the effect.
  39987. */
  39988. ImageProcessingConfiguration.prototype._updateParameters = function () {
  39989. this.onUpdateParameters.notifyObservers(this);
  39990. };
  39991. ImageProcessingConfiguration.prototype.getClassName = function () {
  39992. return "ImageProcessingConfiguration";
  39993. };
  39994. /**
  39995. * Prepare the list of uniforms associated with the Image Processing effects.
  39996. * @param uniformsList The list of uniforms used in the effect
  39997. * @param defines the list of defines currently in use
  39998. */
  39999. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40000. if (defines.EXPOSURE) {
  40001. uniforms.push("exposureLinear");
  40002. }
  40003. if (defines.CONTRAST) {
  40004. uniforms.push("contrast");
  40005. }
  40006. if (defines.COLORGRADING) {
  40007. uniforms.push("colorTransformSettings");
  40008. }
  40009. if (defines.VIGNETTE) {
  40010. uniforms.push("vInverseScreenSize");
  40011. uniforms.push("vignetteSettings1");
  40012. uniforms.push("vignetteSettings2");
  40013. }
  40014. if (defines.COLORCURVES) {
  40015. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40016. }
  40017. };
  40018. /**
  40019. * Prepare the list of samplers associated with the Image Processing effects.
  40020. * @param uniformsList The list of uniforms used in the effect
  40021. * @param defines the list of defines currently in use
  40022. */
  40023. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40024. if (defines.COLORGRADING) {
  40025. samplersList.push("txColorTransform");
  40026. }
  40027. };
  40028. /**
  40029. * Prepare the list of defines associated to the shader.
  40030. * @param defines the list of defines to complete
  40031. */
  40032. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40033. if (forPostProcess === void 0) { forPostProcess = false; }
  40034. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40035. defines.VIGNETTE = false;
  40036. defines.TONEMAPPING = false;
  40037. defines.CONTRAST = false;
  40038. defines.EXPOSURE = false;
  40039. defines.COLORCURVES = false;
  40040. defines.COLORGRADING = false;
  40041. defines.COLORGRADING3D = false;
  40042. defines.IMAGEPROCESSING = false;
  40043. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40044. return;
  40045. }
  40046. defines.VIGNETTE = this.vignetteEnabled;
  40047. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40048. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40049. defines.TONEMAPPING = this.toneMappingEnabled;
  40050. defines.CONTRAST = (this.contrast !== 1.0);
  40051. defines.EXPOSURE = (this.exposure !== 1.0);
  40052. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40053. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40054. if (defines.COLORGRADING) {
  40055. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40056. }
  40057. else {
  40058. defines.COLORGRADING3D = false;
  40059. }
  40060. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40061. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40062. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40063. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40064. };
  40065. /**
  40066. * Returns true if all the image processing information are ready.
  40067. */
  40068. ImageProcessingConfiguration.prototype.isReady = function () {
  40069. // Color Grading texure can not be none blocking.
  40070. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40071. };
  40072. /**
  40073. * Binds the image processing to the shader.
  40074. * @param effect The effect to bind to
  40075. */
  40076. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40077. if (aspectRatio === void 0) { aspectRatio = 1; }
  40078. // Color Curves
  40079. if (this._colorCurvesEnabled && this.colorCurves) {
  40080. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40081. }
  40082. // Vignette
  40083. if (this._vignetteEnabled) {
  40084. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40085. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40086. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40087. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40088. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40089. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40090. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40091. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40092. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40093. var vignettePower = -2.0 * this.vignetteWeight;
  40094. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40095. }
  40096. // Exposure
  40097. effect.setFloat("exposureLinear", this.exposure);
  40098. // Contrast
  40099. effect.setFloat("contrast", this.contrast);
  40100. // Color transform settings
  40101. if (this.colorGradingTexture) {
  40102. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40103. var textureSize = this.colorGradingTexture.getSize().height;
  40104. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40105. 0.5 / textureSize, // textureOffset
  40106. textureSize, // textureSize
  40107. this.colorGradingTexture.level // weight
  40108. );
  40109. }
  40110. };
  40111. /**
  40112. * Clones the current image processing instance.
  40113. * @return The cloned image processing
  40114. */
  40115. ImageProcessingConfiguration.prototype.clone = function () {
  40116. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40117. };
  40118. /**
  40119. * Serializes the current image processing instance to a json representation.
  40120. * @return a JSON representation
  40121. */
  40122. ImageProcessingConfiguration.prototype.serialize = function () {
  40123. return BABYLON.SerializationHelper.Serialize(this);
  40124. };
  40125. /**
  40126. * Parses the image processing from a json representation.
  40127. * @param source the JSON source to parse
  40128. * @return The parsed image processing
  40129. */
  40130. ImageProcessingConfiguration.Parse = function (source) {
  40131. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40132. };
  40133. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40134. /**
  40135. * Used to apply the vignette as a mix with the pixel color.
  40136. */
  40137. get: function () {
  40138. return this._VIGNETTEMODE_MULTIPLY;
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40144. /**
  40145. * Used to apply the vignette as a replacement of the pixel color.
  40146. */
  40147. get: function () {
  40148. return this._VIGNETTEMODE_OPAQUE;
  40149. },
  40150. enumerable: true,
  40151. configurable: true
  40152. });
  40153. // Static constants associated to the image processing.
  40154. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40155. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40156. __decorate([
  40157. BABYLON.serializeAsColorCurves()
  40158. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40159. __decorate([
  40160. BABYLON.serialize()
  40161. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40162. __decorate([
  40163. BABYLON.serializeAsTexture()
  40164. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40165. __decorate([
  40166. BABYLON.serialize()
  40167. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40168. __decorate([
  40169. BABYLON.serialize()
  40170. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40171. __decorate([
  40172. BABYLON.serialize()
  40173. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40174. __decorate([
  40175. BABYLON.serialize()
  40176. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40177. __decorate([
  40178. BABYLON.serialize()
  40179. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40180. __decorate([
  40181. BABYLON.serialize()
  40182. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40183. __decorate([
  40184. BABYLON.serialize()
  40185. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40186. __decorate([
  40187. BABYLON.serialize()
  40188. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40189. __decorate([
  40190. BABYLON.serialize()
  40191. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40192. __decorate([
  40193. BABYLON.serialize()
  40194. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40195. __decorate([
  40196. BABYLON.serializeAsColor4()
  40197. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40198. __decorate([
  40199. BABYLON.serialize()
  40200. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40201. __decorate([
  40202. BABYLON.serialize()
  40203. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40204. __decorate([
  40205. BABYLON.serialize()
  40206. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40207. __decorate([
  40208. BABYLON.serialize()
  40209. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40210. __decorate([
  40211. BABYLON.serialize()
  40212. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40213. return ImageProcessingConfiguration;
  40214. }());
  40215. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40216. })(BABYLON || (BABYLON = {}));
  40217. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40218. "use strict";
  40219. var BABYLON;
  40220. (function (BABYLON) {
  40221. /**
  40222. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40223. * It can help converting any input color in a desired output one. This can then be used to create effects
  40224. * from sepia, black and white to sixties or futuristic rendering...
  40225. *
  40226. * The only supported format is currently 3dl.
  40227. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40228. */
  40229. var ColorGradingTexture = /** @class */ (function (_super) {
  40230. __extends(ColorGradingTexture, _super);
  40231. /**
  40232. * Instantiates a ColorGradingTexture from the following parameters.
  40233. *
  40234. * @param url The location of the color gradind data (currently only supporting 3dl)
  40235. * @param scene The scene the texture will be used in
  40236. */
  40237. function ColorGradingTexture(url, scene) {
  40238. var _this = _super.call(this, scene) || this;
  40239. if (!url) {
  40240. return _this;
  40241. }
  40242. _this._engine = scene.getEngine();
  40243. _this._textureMatrix = BABYLON.Matrix.Identity();
  40244. _this.name = url;
  40245. _this.url = url;
  40246. _this.hasAlpha = false;
  40247. _this.isCube = false;
  40248. _this.is3D = _this._engine.webGLVersion > 1;
  40249. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40250. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40251. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40252. _this.anisotropicFilteringLevel = 1;
  40253. _this._texture = _this._getFromCache(url, true);
  40254. if (!_this._texture) {
  40255. if (!scene.useDelayedTextureLoading) {
  40256. _this.loadTexture();
  40257. }
  40258. else {
  40259. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40260. }
  40261. }
  40262. return _this;
  40263. }
  40264. /**
  40265. * Returns the texture matrix used in most of the material.
  40266. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40267. */
  40268. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40269. return this._textureMatrix;
  40270. };
  40271. /**
  40272. * Occurs when the file being loaded is a .3dl LUT file.
  40273. */
  40274. ColorGradingTexture.prototype.load3dlTexture = function () {
  40275. var engine = this._engine;
  40276. var texture;
  40277. if (engine.webGLVersion === 1) {
  40278. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40279. }
  40280. else {
  40281. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40282. }
  40283. this._texture = texture;
  40284. var callback = function (text) {
  40285. if (typeof text !== "string") {
  40286. return;
  40287. }
  40288. var data = null;
  40289. var tempData = null;
  40290. var line;
  40291. var lines = text.split('\n');
  40292. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40293. var maxColor = 0;
  40294. for (var i = 0; i < lines.length; i++) {
  40295. line = lines[i];
  40296. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40297. continue;
  40298. if (line.indexOf('#') === 0)
  40299. continue;
  40300. var words = line.split(" ");
  40301. if (size === 0) {
  40302. // Number of space + one
  40303. size = words.length;
  40304. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40305. tempData = new Float32Array(size * size * size * 4);
  40306. continue;
  40307. }
  40308. if (size != 0) {
  40309. var r = Math.max(parseInt(words[0]), 0);
  40310. var g = Math.max(parseInt(words[1]), 0);
  40311. var b = Math.max(parseInt(words[2]), 0);
  40312. maxColor = Math.max(r, maxColor);
  40313. maxColor = Math.max(g, maxColor);
  40314. maxColor = Math.max(b, maxColor);
  40315. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40316. if (tempData) {
  40317. tempData[pixelStorageIndex + 0] = r;
  40318. tempData[pixelStorageIndex + 1] = g;
  40319. tempData[pixelStorageIndex + 2] = b;
  40320. }
  40321. pixelIndexSlice++;
  40322. if (pixelIndexSlice % size == 0) {
  40323. pixelIndexH++;
  40324. pixelIndexSlice = 0;
  40325. if (pixelIndexH % size == 0) {
  40326. pixelIndexW++;
  40327. pixelIndexH = 0;
  40328. }
  40329. }
  40330. }
  40331. }
  40332. if (tempData && data) {
  40333. for (var i = 0; i < tempData.length; i++) {
  40334. if (i > 0 && (i + 1) % 4 === 0) {
  40335. data[i] = 255;
  40336. }
  40337. else {
  40338. var value = tempData[i];
  40339. data[i] = (value / maxColor * 255);
  40340. }
  40341. }
  40342. }
  40343. if (texture.is3D) {
  40344. texture.updateSize(size, size, size);
  40345. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40346. }
  40347. else {
  40348. texture.updateSize(size * size, size);
  40349. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40350. }
  40351. };
  40352. var scene = this.getScene();
  40353. if (scene) {
  40354. scene._loadFile(this.url, callback);
  40355. }
  40356. else {
  40357. this._engine._loadFile(this.url, callback);
  40358. }
  40359. return this._texture;
  40360. };
  40361. /**
  40362. * Starts the loading process of the texture.
  40363. */
  40364. ColorGradingTexture.prototype.loadTexture = function () {
  40365. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40366. this.load3dlTexture();
  40367. }
  40368. };
  40369. /**
  40370. * Clones the color gradind texture.
  40371. */
  40372. ColorGradingTexture.prototype.clone = function () {
  40373. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40374. // Base texture
  40375. newTexture.level = this.level;
  40376. return newTexture;
  40377. };
  40378. /**
  40379. * Called during delayed load for textures.
  40380. */
  40381. ColorGradingTexture.prototype.delayLoad = function () {
  40382. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40383. return;
  40384. }
  40385. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40386. this._texture = this._getFromCache(this.url, true);
  40387. if (!this._texture) {
  40388. this.loadTexture();
  40389. }
  40390. };
  40391. /**
  40392. * Parses a color grading texture serialized by Babylon.
  40393. * @param parsedTexture The texture information being parsedTexture
  40394. * @param scene The scene to load the texture in
  40395. * @param rootUrl The root url of the data assets to load
  40396. * @return A color gradind texture
  40397. */
  40398. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40399. var texture = null;
  40400. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40401. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40402. texture.name = parsedTexture.name;
  40403. texture.level = parsedTexture.level;
  40404. }
  40405. return texture;
  40406. };
  40407. /**
  40408. * Serializes the LUT texture to json format.
  40409. */
  40410. ColorGradingTexture.prototype.serialize = function () {
  40411. if (!this.name) {
  40412. return null;
  40413. }
  40414. var serializationObject = {};
  40415. serializationObject.name = this.name;
  40416. serializationObject.level = this.level;
  40417. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40418. return serializationObject;
  40419. };
  40420. /**
  40421. * Empty line regex stored for GC.
  40422. */
  40423. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40424. return ColorGradingTexture;
  40425. }(BABYLON.BaseTexture));
  40426. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40427. })(BABYLON || (BABYLON = {}));
  40428. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40429. "use strict";
  40430. var BABYLON;
  40431. (function (BABYLON) {
  40432. /**
  40433. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40434. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40435. * 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;
  40436. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40437. */
  40438. var ColorCurves = /** @class */ (function () {
  40439. function ColorCurves() {
  40440. this._dirty = true;
  40441. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40442. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40443. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40444. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40445. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40446. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40447. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40448. this._globalHue = 30;
  40449. this._globalDensity = 0;
  40450. this._globalSaturation = 0;
  40451. this._globalExposure = 0;
  40452. this._highlightsHue = 30;
  40453. this._highlightsDensity = 0;
  40454. this._highlightsSaturation = 0;
  40455. this._highlightsExposure = 0;
  40456. this._midtonesHue = 30;
  40457. this._midtonesDensity = 0;
  40458. this._midtonesSaturation = 0;
  40459. this._midtonesExposure = 0;
  40460. this._shadowsHue = 30;
  40461. this._shadowsDensity = 0;
  40462. this._shadowsSaturation = 0;
  40463. this._shadowsExposure = 0;
  40464. }
  40465. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  40466. /**
  40467. * Gets the global Hue value.
  40468. * 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).
  40469. */
  40470. get: function () {
  40471. return this._globalHue;
  40472. },
  40473. /**
  40474. * Sets the global Hue value.
  40475. * 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).
  40476. */
  40477. set: function (value) {
  40478. this._globalHue = value;
  40479. this._dirty = true;
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  40485. /**
  40486. * Gets the global Density value.
  40487. * 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.
  40488. * Values less than zero provide a filter of opposite hue.
  40489. */
  40490. get: function () {
  40491. return this._globalDensity;
  40492. },
  40493. /**
  40494. * Sets the global Density value.
  40495. * 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.
  40496. * Values less than zero provide a filter of opposite hue.
  40497. */
  40498. set: function (value) {
  40499. this._globalDensity = value;
  40500. this._dirty = true;
  40501. },
  40502. enumerable: true,
  40503. configurable: true
  40504. });
  40505. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  40506. /**
  40507. * Gets the global Saturation value.
  40508. * 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.
  40509. */
  40510. get: function () {
  40511. return this._globalSaturation;
  40512. },
  40513. /**
  40514. * Sets the global Saturation value.
  40515. * 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.
  40516. */
  40517. set: function (value) {
  40518. this._globalSaturation = value;
  40519. this._dirty = true;
  40520. },
  40521. enumerable: true,
  40522. configurable: true
  40523. });
  40524. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  40525. /**
  40526. * Gets the highlights Hue value.
  40527. * 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).
  40528. */
  40529. get: function () {
  40530. return this._highlightsHue;
  40531. },
  40532. /**
  40533. * Sets the highlights Hue value.
  40534. * 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).
  40535. */
  40536. set: function (value) {
  40537. this._highlightsHue = value;
  40538. this._dirty = true;
  40539. },
  40540. enumerable: true,
  40541. configurable: true
  40542. });
  40543. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  40544. /**
  40545. * Gets the highlights Density value.
  40546. * 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.
  40547. * Values less than zero provide a filter of opposite hue.
  40548. */
  40549. get: function () {
  40550. return this._highlightsDensity;
  40551. },
  40552. /**
  40553. * Sets the highlights Density value.
  40554. * 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.
  40555. * Values less than zero provide a filter of opposite hue.
  40556. */
  40557. set: function (value) {
  40558. this._highlightsDensity = value;
  40559. this._dirty = true;
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  40565. /**
  40566. * Gets the highlights Saturation value.
  40567. * 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.
  40568. */
  40569. get: function () {
  40570. return this._highlightsSaturation;
  40571. },
  40572. /**
  40573. * Sets the highlights Saturation value.
  40574. * 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.
  40575. */
  40576. set: function (value) {
  40577. this._highlightsSaturation = value;
  40578. this._dirty = true;
  40579. },
  40580. enumerable: true,
  40581. configurable: true
  40582. });
  40583. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  40584. /**
  40585. * Gets the highlights Exposure value.
  40586. * 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.
  40587. */
  40588. get: function () {
  40589. return this._highlightsExposure;
  40590. },
  40591. /**
  40592. * Sets the highlights Exposure value.
  40593. * 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.
  40594. */
  40595. set: function (value) {
  40596. this._highlightsExposure = value;
  40597. this._dirty = true;
  40598. },
  40599. enumerable: true,
  40600. configurable: true
  40601. });
  40602. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  40603. /**
  40604. * Gets the midtones Hue value.
  40605. * 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).
  40606. */
  40607. get: function () {
  40608. return this._midtonesHue;
  40609. },
  40610. /**
  40611. * Sets the midtones Hue value.
  40612. * 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).
  40613. */
  40614. set: function (value) {
  40615. this._midtonesHue = value;
  40616. this._dirty = true;
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  40622. /**
  40623. * Gets the midtones Density value.
  40624. * 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.
  40625. * Values less than zero provide a filter of opposite hue.
  40626. */
  40627. get: function () {
  40628. return this._midtonesDensity;
  40629. },
  40630. /**
  40631. * Sets the midtones Density value.
  40632. * 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.
  40633. * Values less than zero provide a filter of opposite hue.
  40634. */
  40635. set: function (value) {
  40636. this._midtonesDensity = value;
  40637. this._dirty = true;
  40638. },
  40639. enumerable: true,
  40640. configurable: true
  40641. });
  40642. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  40643. /**
  40644. * Gets the midtones Saturation value.
  40645. * 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.
  40646. */
  40647. get: function () {
  40648. return this._midtonesSaturation;
  40649. },
  40650. /**
  40651. * Sets the midtones Saturation value.
  40652. * 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.
  40653. */
  40654. set: function (value) {
  40655. this._midtonesSaturation = value;
  40656. this._dirty = true;
  40657. },
  40658. enumerable: true,
  40659. configurable: true
  40660. });
  40661. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  40662. /**
  40663. * Gets the midtones Exposure value.
  40664. * 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.
  40665. */
  40666. get: function () {
  40667. return this._midtonesExposure;
  40668. },
  40669. /**
  40670. * Sets the midtones Exposure value.
  40671. * 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.
  40672. */
  40673. set: function (value) {
  40674. this._midtonesExposure = value;
  40675. this._dirty = true;
  40676. },
  40677. enumerable: true,
  40678. configurable: true
  40679. });
  40680. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  40681. /**
  40682. * Gets the shadows Hue value.
  40683. * 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).
  40684. */
  40685. get: function () {
  40686. return this._shadowsHue;
  40687. },
  40688. /**
  40689. * Sets the shadows Hue value.
  40690. * 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).
  40691. */
  40692. set: function (value) {
  40693. this._shadowsHue = value;
  40694. this._dirty = true;
  40695. },
  40696. enumerable: true,
  40697. configurable: true
  40698. });
  40699. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  40700. /**
  40701. * Gets the shadows Density value.
  40702. * 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.
  40703. * Values less than zero provide a filter of opposite hue.
  40704. */
  40705. get: function () {
  40706. return this._shadowsDensity;
  40707. },
  40708. /**
  40709. * Sets the shadows Density value.
  40710. * 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.
  40711. * Values less than zero provide a filter of opposite hue.
  40712. */
  40713. set: function (value) {
  40714. this._shadowsDensity = value;
  40715. this._dirty = true;
  40716. },
  40717. enumerable: true,
  40718. configurable: true
  40719. });
  40720. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  40721. /**
  40722. * Gets the shadows Saturation value.
  40723. * 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.
  40724. */
  40725. get: function () {
  40726. return this._shadowsSaturation;
  40727. },
  40728. /**
  40729. * Sets the shadows Saturation value.
  40730. * 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.
  40731. */
  40732. set: function (value) {
  40733. this._shadowsSaturation = value;
  40734. this._dirty = true;
  40735. },
  40736. enumerable: true,
  40737. configurable: true
  40738. });
  40739. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  40740. /**
  40741. * Gets the shadows Exposure value.
  40742. * 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.
  40743. */
  40744. get: function () {
  40745. return this._shadowsExposure;
  40746. },
  40747. /**
  40748. * Sets the shadows Exposure value.
  40749. * 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.
  40750. */
  40751. set: function (value) {
  40752. this._shadowsExposure = value;
  40753. this._dirty = true;
  40754. },
  40755. enumerable: true,
  40756. configurable: true
  40757. });
  40758. ColorCurves.prototype.getClassName = function () {
  40759. return "ColorCurves";
  40760. };
  40761. /**
  40762. * Binds the color curves to the shader.
  40763. * @param colorCurves The color curve to bind
  40764. * @param effect The effect to bind to
  40765. */
  40766. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  40767. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  40768. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  40769. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  40770. if (colorCurves._dirty) {
  40771. colorCurves._dirty = false;
  40772. // Fill in global info.
  40773. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  40774. // Compute highlights info.
  40775. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  40776. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  40777. // Compute midtones info.
  40778. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  40779. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  40780. // Compute shadows info.
  40781. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  40782. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  40783. // Compute deltas (neutral is midtones).
  40784. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  40785. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  40786. }
  40787. if (effect) {
  40788. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  40789. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  40790. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  40791. }
  40792. };
  40793. /**
  40794. * Prepare the list of uniforms associated with the ColorCurves effects.
  40795. * @param uniformsList The list of uniforms used in the effect
  40796. */
  40797. ColorCurves.PrepareUniforms = function (uniformsList) {
  40798. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  40799. };
  40800. /**
  40801. * Returns color grading data based on a hue, density, saturation and exposure value.
  40802. * @param filterHue The hue of the color filter.
  40803. * @param filterDensity The density of the color filter.
  40804. * @param saturation The saturation.
  40805. * @param exposure The exposure.
  40806. * @param result The result data container.
  40807. */
  40808. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  40809. if (hue == null) {
  40810. return;
  40811. }
  40812. hue = ColorCurves.clamp(hue, 0, 360);
  40813. density = ColorCurves.clamp(density, -100, 100);
  40814. saturation = ColorCurves.clamp(saturation, -100, 100);
  40815. exposure = ColorCurves.clamp(exposure, -100, 100);
  40816. // Remap the slider/config filter density with non-linear mapping and also scale by half
  40817. // so that the maximum filter density is only 50% control. This provides fine control
  40818. // for small values and reasonable range.
  40819. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  40820. density *= 0.5;
  40821. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  40822. if (density < 0) {
  40823. density *= -1;
  40824. hue = (hue + 180) % 360;
  40825. }
  40826. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  40827. result.scaleToRef(2, result);
  40828. result.a = 1 + 0.01 * saturation;
  40829. };
  40830. /**
  40831. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  40832. * @param value The input slider value in range [-100,100].
  40833. * @returns Adjusted value.
  40834. */
  40835. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  40836. value /= 100;
  40837. var x = Math.abs(value);
  40838. x = Math.pow(x, 2);
  40839. if (value < 0) {
  40840. x *= -1;
  40841. }
  40842. x *= 100;
  40843. return x;
  40844. };
  40845. /**
  40846. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  40847. * @param hue The hue (H) input.
  40848. * @param saturation The saturation (S) input.
  40849. * @param brightness The brightness (B) input.
  40850. * @result An RGBA color represented as Vector4.
  40851. */
  40852. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  40853. var h = ColorCurves.clamp(hue, 0, 360);
  40854. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  40855. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  40856. if (s === 0) {
  40857. result.r = v;
  40858. result.g = v;
  40859. result.b = v;
  40860. }
  40861. else {
  40862. // sector 0 to 5
  40863. h /= 60;
  40864. var i = Math.floor(h);
  40865. // fractional part of h
  40866. var f = h - i;
  40867. var p = v * (1 - s);
  40868. var q = v * (1 - s * f);
  40869. var t = v * (1 - s * (1 - f));
  40870. switch (i) {
  40871. case 0:
  40872. result.r = v;
  40873. result.g = t;
  40874. result.b = p;
  40875. break;
  40876. case 1:
  40877. result.r = q;
  40878. result.g = v;
  40879. result.b = p;
  40880. break;
  40881. case 2:
  40882. result.r = p;
  40883. result.g = v;
  40884. result.b = t;
  40885. break;
  40886. case 3:
  40887. result.r = p;
  40888. result.g = q;
  40889. result.b = v;
  40890. break;
  40891. case 4:
  40892. result.r = t;
  40893. result.g = p;
  40894. result.b = v;
  40895. break;
  40896. default:// case 5:
  40897. result.r = v;
  40898. result.g = p;
  40899. result.b = q;
  40900. break;
  40901. }
  40902. }
  40903. result.a = 1;
  40904. };
  40905. /**
  40906. * Returns a value clamped between min and max
  40907. * @param value The value to clamp
  40908. * @param min The minimum of value
  40909. * @param max The maximum of value
  40910. * @returns The clamped value.
  40911. */
  40912. ColorCurves.clamp = function (value, min, max) {
  40913. return Math.min(Math.max(value, min), max);
  40914. };
  40915. /**
  40916. * Clones the current color curve instance.
  40917. * @return The cloned curves
  40918. */
  40919. ColorCurves.prototype.clone = function () {
  40920. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  40921. };
  40922. /**
  40923. * Serializes the current color curve instance to a json representation.
  40924. * @return a JSON representation
  40925. */
  40926. ColorCurves.prototype.serialize = function () {
  40927. return BABYLON.SerializationHelper.Serialize(this);
  40928. };
  40929. /**
  40930. * Parses the color curve from a json representation.
  40931. * @param source the JSON source to parse
  40932. * @return The parsed curves
  40933. */
  40934. ColorCurves.Parse = function (source) {
  40935. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  40936. };
  40937. __decorate([
  40938. BABYLON.serialize()
  40939. ], ColorCurves.prototype, "_globalHue", void 0);
  40940. __decorate([
  40941. BABYLON.serialize()
  40942. ], ColorCurves.prototype, "_globalDensity", void 0);
  40943. __decorate([
  40944. BABYLON.serialize()
  40945. ], ColorCurves.prototype, "_globalSaturation", void 0);
  40946. __decorate([
  40947. BABYLON.serialize()
  40948. ], ColorCurves.prototype, "_globalExposure", void 0);
  40949. __decorate([
  40950. BABYLON.serialize()
  40951. ], ColorCurves.prototype, "_highlightsHue", void 0);
  40952. __decorate([
  40953. BABYLON.serialize()
  40954. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  40955. __decorate([
  40956. BABYLON.serialize()
  40957. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  40958. __decorate([
  40959. BABYLON.serialize()
  40960. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  40961. __decorate([
  40962. BABYLON.serialize()
  40963. ], ColorCurves.prototype, "_midtonesHue", void 0);
  40964. __decorate([
  40965. BABYLON.serialize()
  40966. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  40967. __decorate([
  40968. BABYLON.serialize()
  40969. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  40970. __decorate([
  40971. BABYLON.serialize()
  40972. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  40973. return ColorCurves;
  40974. }());
  40975. BABYLON.ColorCurves = ColorCurves;
  40976. })(BABYLON || (BABYLON = {}));
  40977. //# sourceMappingURL=babylon.colorCurves.js.map
  40978. "use strict";
  40979. //# sourceMappingURL=babylon.behavior.js.map
  40980. "use strict";
  40981. var BABYLON;
  40982. (function (BABYLON) {
  40983. /**
  40984. * "Static Class" containing the most commonly used helper while dealing with material for
  40985. * rendering purpose.
  40986. *
  40987. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40988. *
  40989. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40990. */
  40991. var MaterialHelper = /** @class */ (function () {
  40992. function MaterialHelper() {
  40993. }
  40994. /**
  40995. * Bind the current view position to an effect.
  40996. * @param effect The effect to be bound
  40997. * @param scene The scene the eyes position is used from
  40998. */
  40999. MaterialHelper.BindEyePosition = function (effect, scene) {
  41000. if (scene._forcedViewPosition) {
  41001. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41002. return;
  41003. }
  41004. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41005. };
  41006. /**
  41007. * Helps preparing the defines values about the UVs in used in the effect.
  41008. * UVs are shared as much as we can accross chanels in the shaders.
  41009. * @param texture The texture we are preparing the UVs for
  41010. * @param defines The defines to update
  41011. * @param key The chanel key "diffuse", "specular"... used in the shader
  41012. */
  41013. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41014. defines._needUVs = true;
  41015. defines[key] = true;
  41016. if (texture.getTextureMatrix().isIdentity(true)) {
  41017. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41018. if (texture.coordinatesIndex === 0) {
  41019. defines["MAINUV1"] = true;
  41020. }
  41021. else {
  41022. defines["MAINUV2"] = true;
  41023. }
  41024. }
  41025. else {
  41026. defines[key + "DIRECTUV"] = 0;
  41027. }
  41028. };
  41029. /**
  41030. * Binds a texture matrix value to its corrsponding uniform
  41031. * @param texture The texture to bind the matrix for
  41032. * @param uniformBuffer The uniform buffer receivin the data
  41033. * @param key The chanel key "diffuse", "specular"... used in the shader
  41034. */
  41035. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41036. var matrix = texture.getTextureMatrix();
  41037. if (!matrix.isIdentity(true)) {
  41038. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41039. }
  41040. };
  41041. /**
  41042. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41043. * @param mesh defines the current mesh
  41044. * @param scene defines the current scene
  41045. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41046. * @param pointsCloud defines if point cloud rendering has to be turned on
  41047. * @param fogEnabled defines if fog has to be turned on
  41048. * @param alphaTest defines if alpha testing has to be turned on
  41049. * @param defines defines the current list of defines
  41050. */
  41051. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41052. if (defines._areMiscDirty) {
  41053. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41054. defines["POINTSIZE"] = pointsCloud;
  41055. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41056. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41057. defines["ALPHATEST"] = alphaTest;
  41058. }
  41059. };
  41060. /**
  41061. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41062. * @param scene defines the current scene
  41063. * @param engine defines the current engine
  41064. * @param defines specifies the list of active defines
  41065. * @param useInstances defines if instances have to be turned on
  41066. * @param useClipPlane defines if clip plane have to be turned on
  41067. */
  41068. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41069. if (useClipPlane === void 0) { useClipPlane = null; }
  41070. var changed = false;
  41071. if (useClipPlane == null) {
  41072. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41073. }
  41074. if (defines["CLIPPLANE"] !== useClipPlane) {
  41075. defines["CLIPPLANE"] = useClipPlane;
  41076. changed = true;
  41077. }
  41078. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41079. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41080. changed = true;
  41081. }
  41082. if (defines["INSTANCES"] !== useInstances) {
  41083. defines["INSTANCES"] = useInstances;
  41084. changed = true;
  41085. }
  41086. if (changed) {
  41087. defines.markAsUnprocessed();
  41088. }
  41089. };
  41090. /**
  41091. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41092. * @param mesh The mesh containing the geometry data we will draw
  41093. * @param defines The defines to update
  41094. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41095. * @param useBones Precise whether bones should be used or not (override mesh info)
  41096. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41097. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41098. * @returns false if defines are considered not dirty and have not been checked
  41099. */
  41100. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41101. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41102. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41103. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41104. return false;
  41105. }
  41106. defines._normals = defines._needNormals;
  41107. defines._uvs = defines._needUVs;
  41108. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41109. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41110. defines["TANGENT"] = true;
  41111. }
  41112. if (defines._needUVs) {
  41113. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41114. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41115. }
  41116. else {
  41117. defines["UV1"] = false;
  41118. defines["UV2"] = false;
  41119. }
  41120. if (useVertexColor) {
  41121. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41122. defines["VERTEXCOLOR"] = hasVertexColors;
  41123. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41124. }
  41125. if (useBones) {
  41126. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41127. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41128. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41129. }
  41130. else {
  41131. defines["NUM_BONE_INFLUENCERS"] = 0;
  41132. defines["BonesPerMesh"] = 0;
  41133. }
  41134. }
  41135. if (useMorphTargets) {
  41136. var manager = mesh.morphTargetManager;
  41137. if (manager) {
  41138. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41139. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41140. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41141. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41142. }
  41143. else {
  41144. defines["MORPHTARGETS_TANGENT"] = false;
  41145. defines["MORPHTARGETS_NORMAL"] = false;
  41146. defines["MORPHTARGETS"] = false;
  41147. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41148. }
  41149. }
  41150. return true;
  41151. };
  41152. /**
  41153. * Prepares the defines related to the light information passed in parameter
  41154. * @param scene The scene we are intending to draw
  41155. * @param mesh The mesh the effect is compiling for
  41156. * @param defines The defines to update
  41157. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41158. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41159. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41160. * @returns true if normals will be required for the rest of the effect
  41161. */
  41162. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41163. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41164. if (disableLighting === void 0) { disableLighting = false; }
  41165. if (!defines._areLightsDirty) {
  41166. return defines._needNormals;
  41167. }
  41168. var lightIndex = 0;
  41169. var needNormals = false;
  41170. var needRebuild = false;
  41171. var lightmapMode = false;
  41172. var shadowEnabled = false;
  41173. var specularEnabled = false;
  41174. if (scene.lightsEnabled && !disableLighting) {
  41175. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41176. var light = _a[_i];
  41177. needNormals = true;
  41178. if (defines["LIGHT" + lightIndex] === undefined) {
  41179. needRebuild = true;
  41180. }
  41181. defines["LIGHT" + lightIndex] = true;
  41182. defines["SPOTLIGHT" + lightIndex] = false;
  41183. defines["HEMILIGHT" + lightIndex] = false;
  41184. defines["POINTLIGHT" + lightIndex] = false;
  41185. defines["DIRLIGHT" + lightIndex] = false;
  41186. var type;
  41187. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41188. type = "SPOTLIGHT" + lightIndex;
  41189. var spotLight = light;
  41190. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41191. }
  41192. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41193. type = "HEMILIGHT" + lightIndex;
  41194. }
  41195. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41196. type = "POINTLIGHT" + lightIndex;
  41197. }
  41198. else {
  41199. type = "DIRLIGHT" + lightIndex;
  41200. }
  41201. defines[type] = true;
  41202. // Specular
  41203. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41204. specularEnabled = true;
  41205. }
  41206. // Shadows
  41207. defines["SHADOW" + lightIndex] = false;
  41208. defines["SHADOWPCF" + lightIndex] = false;
  41209. defines["SHADOWPCSS" + lightIndex] = false;
  41210. defines["SHADOWPOISSON" + lightIndex] = false;
  41211. defines["SHADOWESM" + lightIndex] = false;
  41212. defines["SHADOWCUBE" + lightIndex] = false;
  41213. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41214. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41215. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41216. var shadowGenerator = light.getShadowGenerator();
  41217. if (shadowGenerator) {
  41218. shadowEnabled = true;
  41219. shadowGenerator.prepareDefines(defines, lightIndex);
  41220. }
  41221. }
  41222. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41223. lightmapMode = true;
  41224. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41225. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41226. }
  41227. else {
  41228. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41229. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41230. }
  41231. lightIndex++;
  41232. if (lightIndex === maxSimultaneousLights)
  41233. break;
  41234. }
  41235. }
  41236. defines["SPECULARTERM"] = specularEnabled;
  41237. defines["SHADOWS"] = shadowEnabled;
  41238. // Resetting all other lights if any
  41239. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41240. if (defines["LIGHT" + index] !== undefined) {
  41241. defines["LIGHT" + index] = false;
  41242. defines["HEMILIGHT" + lightIndex] = false;
  41243. defines["POINTLIGHT" + lightIndex] = false;
  41244. defines["DIRLIGHT" + lightIndex] = false;
  41245. defines["SPOTLIGHT" + lightIndex] = false;
  41246. defines["SHADOW" + lightIndex] = false;
  41247. }
  41248. }
  41249. var caps = scene.getEngine().getCaps();
  41250. if (defines["SHADOWFLOAT"] === undefined) {
  41251. needRebuild = true;
  41252. }
  41253. defines["SHADOWFLOAT"] = shadowEnabled &&
  41254. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41255. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41256. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41257. if (needRebuild) {
  41258. defines.rebuild();
  41259. }
  41260. return needNormals;
  41261. };
  41262. /**
  41263. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41264. * that won t be acctive due to defines being turned off.
  41265. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41266. * @param samplersList The samplers list
  41267. * @param defines The defines helping in the list generation
  41268. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41269. */
  41270. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41271. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41272. var uniformsList;
  41273. var uniformBuffersList = null;
  41274. if (uniformsListOrOptions.uniformsNames) {
  41275. var options = uniformsListOrOptions;
  41276. uniformsList = options.uniformsNames;
  41277. uniformBuffersList = options.uniformBuffersNames;
  41278. samplersList = options.samplers;
  41279. defines = options.defines;
  41280. maxSimultaneousLights = options.maxSimultaneousLights;
  41281. }
  41282. else {
  41283. uniformsList = uniformsListOrOptions;
  41284. if (!samplersList) {
  41285. samplersList = [];
  41286. }
  41287. }
  41288. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41289. if (!defines["LIGHT" + lightIndex]) {
  41290. break;
  41291. }
  41292. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41293. if (uniformBuffersList) {
  41294. uniformBuffersList.push("Light" + lightIndex);
  41295. }
  41296. samplersList.push("shadowSampler" + lightIndex);
  41297. samplersList.push("depthSampler" + lightIndex);
  41298. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41299. samplersList.push("projectionLightSampler" + lightIndex);
  41300. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41301. }
  41302. }
  41303. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41304. uniformsList.push("morphTargetInfluences");
  41305. }
  41306. };
  41307. /**
  41308. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41309. * @param defines The defines to update while falling back
  41310. * @param fallbacks The authorized effect fallbacks
  41311. * @param maxSimultaneousLights The maximum number of lights allowed
  41312. * @param rank the current rank of the Effect
  41313. * @returns The newly affected rank
  41314. */
  41315. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41316. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41317. if (rank === void 0) { rank = 0; }
  41318. var lightFallbackRank = 0;
  41319. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41320. if (!defines["LIGHT" + lightIndex]) {
  41321. break;
  41322. }
  41323. if (lightIndex > 0) {
  41324. lightFallbackRank = rank + lightIndex;
  41325. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41326. }
  41327. if (!defines["SHADOWS"]) {
  41328. if (defines["SHADOW" + lightIndex]) {
  41329. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41330. }
  41331. if (defines["SHADOWPCF" + lightIndex]) {
  41332. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41333. }
  41334. if (defines["SHADOWPCSS" + lightIndex]) {
  41335. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41336. }
  41337. if (defines["SHADOWPOISSON" + lightIndex]) {
  41338. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41339. }
  41340. if (defines["SHADOWESM" + lightIndex]) {
  41341. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41342. }
  41343. }
  41344. }
  41345. return lightFallbackRank++;
  41346. };
  41347. /**
  41348. * Prepares the list of attributes required for morph targets according to the effect defines.
  41349. * @param attribs The current list of supported attribs
  41350. * @param mesh The mesh to prepare the morph targets attributes for
  41351. * @param defines The current Defines of the effect
  41352. */
  41353. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41354. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41355. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41356. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41357. var manager = mesh.morphTargetManager;
  41358. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41359. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41360. for (var index = 0; index < influencers; index++) {
  41361. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41362. if (normal) {
  41363. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41364. }
  41365. if (tangent) {
  41366. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41367. }
  41368. if (attribs.length > maxAttributesCount) {
  41369. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41370. }
  41371. }
  41372. }
  41373. };
  41374. /**
  41375. * Prepares the list of attributes required for bones according to the effect defines.
  41376. * @param attribs The current list of supported attribs
  41377. * @param mesh The mesh to prepare the bones attributes for
  41378. * @param defines The current Defines of the effect
  41379. * @param fallbacks The current efffect fallback strategy
  41380. */
  41381. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41382. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41383. fallbacks.addCPUSkinningFallback(0, mesh);
  41384. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41385. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41386. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41387. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41388. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41389. }
  41390. }
  41391. };
  41392. /**
  41393. * Prepares the list of attributes required for instances according to the effect defines.
  41394. * @param attribs The current list of supported attribs
  41395. * @param defines The current Defines of the effect
  41396. */
  41397. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41398. if (defines["INSTANCES"]) {
  41399. attribs.push("world0");
  41400. attribs.push("world1");
  41401. attribs.push("world2");
  41402. attribs.push("world3");
  41403. }
  41404. };
  41405. /**
  41406. * Binds the light shadow information to the effect for the given mesh.
  41407. * @param light The light containing the generator
  41408. * @param scene The scene the lights belongs to
  41409. * @param mesh The mesh we are binding the information to render
  41410. * @param lightIndex The light index in the effect used to render the mesh
  41411. * @param effect The effect we are binding the data to
  41412. */
  41413. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41414. if (light.shadowEnabled && mesh.receiveShadows) {
  41415. var shadowGenerator = light.getShadowGenerator();
  41416. if (shadowGenerator) {
  41417. shadowGenerator.bindShadowLight(lightIndex, effect);
  41418. }
  41419. }
  41420. };
  41421. /**
  41422. * Binds the light information to the effect.
  41423. * @param light The light containing the generator
  41424. * @param effect The effect we are binding the data to
  41425. * @param lightIndex The light index in the effect used to render
  41426. */
  41427. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41428. light.transferToEffect(effect, lightIndex + "");
  41429. };
  41430. /**
  41431. * Binds the lights information from the scene to the effect for the given mesh.
  41432. * @param scene The scene the lights belongs to
  41433. * @param mesh The mesh we are binding the information to render
  41434. * @param effect The effect we are binding the data to
  41435. * @param defines The generated defines for the effect
  41436. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41437. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41438. */
  41439. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41440. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41441. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41442. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41443. for (var i = 0; i < len; i++) {
  41444. var light = mesh._lightSources[i];
  41445. var iAsString = i.toString();
  41446. var scaledIntensity = light.getScaledIntensity();
  41447. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41448. MaterialHelper.BindLightProperties(light, effect, i);
  41449. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41450. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41451. if (defines["SPECULARTERM"]) {
  41452. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41453. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41454. }
  41455. // Shadows
  41456. if (scene.shadowsEnabled) {
  41457. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41458. }
  41459. light._uniformBuffer.update();
  41460. }
  41461. };
  41462. /**
  41463. * Binds the fog information from the scene to the effect for the given mesh.
  41464. * @param scene The scene the lights belongs to
  41465. * @param mesh The mesh we are binding the information to render
  41466. * @param effect The effect we are binding the data to
  41467. */
  41468. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41469. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41470. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41471. effect.setColor3("vFogColor", scene.fogColor);
  41472. }
  41473. };
  41474. /**
  41475. * Binds the bones information from the mesh to the effect.
  41476. * @param mesh The mesh we are binding the information to render
  41477. * @param effect The effect we are binding the data to
  41478. */
  41479. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41480. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41481. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41482. if (matrices && effect) {
  41483. effect.setMatrices("mBones", matrices);
  41484. }
  41485. }
  41486. };
  41487. /**
  41488. * Binds the morph targets information from the mesh to the effect.
  41489. * @param abstractMesh The mesh we are binding the information to render
  41490. * @param effect The effect we are binding the data to
  41491. */
  41492. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41493. var manager = abstractMesh.morphTargetManager;
  41494. if (!abstractMesh || !manager) {
  41495. return;
  41496. }
  41497. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41498. };
  41499. /**
  41500. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41501. * @param defines The generated defines used in the effect
  41502. * @param effect The effect we are binding the data to
  41503. * @param scene The scene we are willing to render with logarithmic scale for
  41504. */
  41505. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41506. if (defines["LOGARITHMICDEPTH"]) {
  41507. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41508. }
  41509. };
  41510. /**
  41511. * Binds the clip plane information from the scene to the effect.
  41512. * @param scene The scene the clip plane information are extracted from
  41513. * @param effect The effect we are binding the data to
  41514. */
  41515. MaterialHelper.BindClipPlane = function (effect, scene) {
  41516. if (scene.clipPlane) {
  41517. var clipPlane = scene.clipPlane;
  41518. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41519. }
  41520. };
  41521. return MaterialHelper;
  41522. }());
  41523. BABYLON.MaterialHelper = MaterialHelper;
  41524. })(BABYLON || (BABYLON = {}));
  41525. //# sourceMappingURL=babylon.materialHelper.js.map
  41526. "use strict";
  41527. var BABYLON;
  41528. (function (BABYLON) {
  41529. var PushMaterial = /** @class */ (function (_super) {
  41530. __extends(PushMaterial, _super);
  41531. function PushMaterial(name, scene) {
  41532. var _this = _super.call(this, name, scene) || this;
  41533. _this._normalMatrix = new BABYLON.Matrix();
  41534. _this.storeEffectOnSubMeshes = true;
  41535. return _this;
  41536. }
  41537. PushMaterial.prototype.getEffect = function () {
  41538. return this._activeEffect;
  41539. };
  41540. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41541. if (!mesh) {
  41542. return false;
  41543. }
  41544. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41545. return true;
  41546. }
  41547. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41548. };
  41549. /**
  41550. * Binds the given world matrix to the active effect
  41551. *
  41552. * @param world the matrix to bind
  41553. */
  41554. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41555. this._activeEffect.setMatrix("world", world);
  41556. };
  41557. /**
  41558. * Binds the given normal matrix to the active effect
  41559. *
  41560. * @param normalMatrix the matrix to bind
  41561. */
  41562. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41563. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41564. };
  41565. PushMaterial.prototype.bind = function (world, mesh) {
  41566. if (!mesh) {
  41567. return;
  41568. }
  41569. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41570. };
  41571. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41572. if (effect === void 0) { effect = null; }
  41573. _super.prototype._afterBind.call(this, mesh);
  41574. this.getScene()._cachedEffect = effect;
  41575. };
  41576. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41577. if (visibility === void 0) { visibility = 1; }
  41578. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41579. };
  41580. return PushMaterial;
  41581. }(BABYLON.Material));
  41582. BABYLON.PushMaterial = PushMaterial;
  41583. })(BABYLON || (BABYLON = {}));
  41584. //# sourceMappingURL=babylon.pushMaterial.js.map
  41585. "use strict";
  41586. var BABYLON;
  41587. (function (BABYLON) {
  41588. /** @ignore */
  41589. var StandardMaterialDefines = /** @class */ (function (_super) {
  41590. __extends(StandardMaterialDefines, _super);
  41591. function StandardMaterialDefines() {
  41592. var _this = _super.call(this) || this;
  41593. _this.MAINUV1 = false;
  41594. _this.MAINUV2 = false;
  41595. _this.DIFFUSE = false;
  41596. _this.DIFFUSEDIRECTUV = 0;
  41597. _this.AMBIENT = false;
  41598. _this.AMBIENTDIRECTUV = 0;
  41599. _this.OPACITY = false;
  41600. _this.OPACITYDIRECTUV = 0;
  41601. _this.OPACITYRGB = false;
  41602. _this.REFLECTION = false;
  41603. _this.EMISSIVE = false;
  41604. _this.EMISSIVEDIRECTUV = 0;
  41605. _this.SPECULAR = false;
  41606. _this.SPECULARDIRECTUV = 0;
  41607. _this.BUMP = false;
  41608. _this.BUMPDIRECTUV = 0;
  41609. _this.PARALLAX = false;
  41610. _this.PARALLAXOCCLUSION = false;
  41611. _this.SPECULAROVERALPHA = false;
  41612. _this.CLIPPLANE = false;
  41613. _this.ALPHATEST = false;
  41614. _this.DEPTHPREPASS = false;
  41615. _this.ALPHAFROMDIFFUSE = false;
  41616. _this.POINTSIZE = false;
  41617. _this.FOG = false;
  41618. _this.SPECULARTERM = false;
  41619. _this.DIFFUSEFRESNEL = false;
  41620. _this.OPACITYFRESNEL = false;
  41621. _this.REFLECTIONFRESNEL = false;
  41622. _this.REFRACTIONFRESNEL = false;
  41623. _this.EMISSIVEFRESNEL = false;
  41624. _this.FRESNEL = false;
  41625. _this.NORMAL = false;
  41626. _this.UV1 = false;
  41627. _this.UV2 = false;
  41628. _this.VERTEXCOLOR = false;
  41629. _this.VERTEXALPHA = false;
  41630. _this.NUM_BONE_INFLUENCERS = 0;
  41631. _this.BonesPerMesh = 0;
  41632. _this.INSTANCES = false;
  41633. _this.GLOSSINESS = false;
  41634. _this.ROUGHNESS = false;
  41635. _this.EMISSIVEASILLUMINATION = false;
  41636. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41637. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41638. _this.LIGHTMAP = false;
  41639. _this.LIGHTMAPDIRECTUV = 0;
  41640. _this.OBJECTSPACE_NORMALMAP = false;
  41641. _this.USELIGHTMAPASSHADOWMAP = false;
  41642. _this.REFLECTIONMAP_3D = false;
  41643. _this.REFLECTIONMAP_SPHERICAL = false;
  41644. _this.REFLECTIONMAP_PLANAR = false;
  41645. _this.REFLECTIONMAP_CUBIC = false;
  41646. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41647. _this.REFLECTIONMAP_PROJECTION = false;
  41648. _this.REFLECTIONMAP_SKYBOX = false;
  41649. _this.REFLECTIONMAP_EXPLICIT = false;
  41650. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41651. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41652. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41653. _this.INVERTCUBICMAP = false;
  41654. _this.LOGARITHMICDEPTH = false;
  41655. _this.REFRACTION = false;
  41656. _this.REFRACTIONMAP_3D = false;
  41657. _this.REFLECTIONOVERALPHA = false;
  41658. _this.TWOSIDEDLIGHTING = false;
  41659. _this.SHADOWFLOAT = false;
  41660. _this.MORPHTARGETS = false;
  41661. _this.MORPHTARGETS_NORMAL = false;
  41662. _this.MORPHTARGETS_TANGENT = false;
  41663. _this.NUM_MORPH_INFLUENCERS = 0;
  41664. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41665. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41666. _this.IMAGEPROCESSING = false;
  41667. _this.VIGNETTE = false;
  41668. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41669. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41670. _this.TONEMAPPING = false;
  41671. _this.CONTRAST = false;
  41672. _this.COLORCURVES = false;
  41673. _this.COLORGRADING = false;
  41674. _this.COLORGRADING3D = false;
  41675. _this.SAMPLER3DGREENDEPTH = false;
  41676. _this.SAMPLER3DBGRMAP = false;
  41677. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41678. _this.EXPOSURE = false;
  41679. _this.rebuild();
  41680. return _this;
  41681. }
  41682. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41683. var modes = [
  41684. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41685. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41686. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41687. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41688. ];
  41689. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41690. var mode = modes_1[_i];
  41691. this[mode] = (mode === modeToEnable);
  41692. }
  41693. };
  41694. return StandardMaterialDefines;
  41695. }(BABYLON.MaterialDefines));
  41696. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41697. var StandardMaterial = /** @class */ (function (_super) {
  41698. __extends(StandardMaterial, _super);
  41699. function StandardMaterial(name, scene) {
  41700. var _this = _super.call(this, name, scene) || this;
  41701. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41702. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41703. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41704. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41705. _this.specularPower = 64;
  41706. _this._useAlphaFromDiffuseTexture = false;
  41707. _this._useEmissiveAsIllumination = false;
  41708. _this._linkEmissiveWithDiffuse = false;
  41709. _this._useSpecularOverAlpha = false;
  41710. _this._useReflectionOverAlpha = false;
  41711. _this._disableLighting = false;
  41712. _this._useObjectSpaceNormalMap = false;
  41713. _this._useParallax = false;
  41714. _this._useParallaxOcclusion = false;
  41715. _this.parallaxScaleBias = 0.05;
  41716. _this._roughness = 0;
  41717. _this.indexOfRefraction = 0.98;
  41718. _this.invertRefractionY = true;
  41719. _this._useLightmapAsShadowmap = false;
  41720. _this._useReflectionFresnelFromSpecular = false;
  41721. _this._useGlossinessFromSpecularMapAlpha = false;
  41722. _this._maxSimultaneousLights = 4;
  41723. /**
  41724. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41725. */
  41726. _this._invertNormalMapX = false;
  41727. /**
  41728. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41729. */
  41730. _this._invertNormalMapY = false;
  41731. /**
  41732. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41733. */
  41734. _this._twoSidedLighting = false;
  41735. _this._renderTargets = new BABYLON.SmartArray(16);
  41736. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41737. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41738. // Setup the default processing configuration to the scene.
  41739. _this._attachImageProcessingConfiguration(null);
  41740. _this.getRenderTargetTextures = function () {
  41741. _this._renderTargets.reset();
  41742. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41743. _this._renderTargets.push(_this._reflectionTexture);
  41744. }
  41745. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41746. _this._renderTargets.push(_this._refractionTexture);
  41747. }
  41748. return _this._renderTargets;
  41749. };
  41750. return _this;
  41751. }
  41752. ;
  41753. ;
  41754. ;
  41755. ;
  41756. ;
  41757. ;
  41758. ;
  41759. ;
  41760. ;
  41761. ;
  41762. ;
  41763. ;
  41764. ;
  41765. ;
  41766. ;
  41767. ;
  41768. ;
  41769. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41770. /**
  41771. * Gets the image processing configuration used either in this material.
  41772. */
  41773. get: function () {
  41774. return this._imageProcessingConfiguration;
  41775. },
  41776. /**
  41777. * Sets the Default image processing configuration used either in the this material.
  41778. *
  41779. * If sets to null, the scene one is in use.
  41780. */
  41781. set: function (value) {
  41782. this._attachImageProcessingConfiguration(value);
  41783. // Ensure the effect will be rebuilt.
  41784. this._markAllSubMeshesAsTexturesDirty();
  41785. },
  41786. enumerable: true,
  41787. configurable: true
  41788. });
  41789. /**
  41790. * Attaches a new image processing configuration to the Standard Material.
  41791. * @param configuration
  41792. */
  41793. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41794. var _this = this;
  41795. if (configuration === this._imageProcessingConfiguration) {
  41796. return;
  41797. }
  41798. // Detaches observer.
  41799. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41800. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41801. }
  41802. // Pick the scene configuration if needed.
  41803. if (!configuration) {
  41804. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41805. }
  41806. else {
  41807. this._imageProcessingConfiguration = configuration;
  41808. }
  41809. // Attaches observer.
  41810. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41811. _this._markAllSubMeshesAsImageProcessingDirty();
  41812. });
  41813. };
  41814. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41815. /**
  41816. * Gets wether the color curves effect is enabled.
  41817. */
  41818. get: function () {
  41819. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41820. },
  41821. /**
  41822. * Sets wether the color curves effect is enabled.
  41823. */
  41824. set: function (value) {
  41825. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41826. },
  41827. enumerable: true,
  41828. configurable: true
  41829. });
  41830. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41831. /**
  41832. * Gets wether the color grading effect is enabled.
  41833. */
  41834. get: function () {
  41835. return this.imageProcessingConfiguration.colorGradingEnabled;
  41836. },
  41837. /**
  41838. * Gets wether the color grading effect is enabled.
  41839. */
  41840. set: function (value) {
  41841. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41842. },
  41843. enumerable: true,
  41844. configurable: true
  41845. });
  41846. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41847. /**
  41848. * Gets wether tonemapping is enabled or not.
  41849. */
  41850. get: function () {
  41851. return this._imageProcessingConfiguration.toneMappingEnabled;
  41852. },
  41853. /**
  41854. * Sets wether tonemapping is enabled or not
  41855. */
  41856. set: function (value) {
  41857. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41858. },
  41859. enumerable: true,
  41860. configurable: true
  41861. });
  41862. ;
  41863. ;
  41864. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41865. /**
  41866. * The camera exposure used on this material.
  41867. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41868. * This corresponds to a photographic exposure.
  41869. */
  41870. get: function () {
  41871. return this._imageProcessingConfiguration.exposure;
  41872. },
  41873. /**
  41874. * The camera exposure used on this material.
  41875. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41876. * This corresponds to a photographic exposure.
  41877. */
  41878. set: function (value) {
  41879. this._imageProcessingConfiguration.exposure = value;
  41880. },
  41881. enumerable: true,
  41882. configurable: true
  41883. });
  41884. ;
  41885. ;
  41886. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41887. /**
  41888. * Gets The camera contrast used on this material.
  41889. */
  41890. get: function () {
  41891. return this._imageProcessingConfiguration.contrast;
  41892. },
  41893. /**
  41894. * Sets The camera contrast used on this material.
  41895. */
  41896. set: function (value) {
  41897. this._imageProcessingConfiguration.contrast = value;
  41898. },
  41899. enumerable: true,
  41900. configurable: true
  41901. });
  41902. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41903. /**
  41904. * Gets the Color Grading 2D Lookup Texture.
  41905. */
  41906. get: function () {
  41907. return this._imageProcessingConfiguration.colorGradingTexture;
  41908. },
  41909. /**
  41910. * Sets the Color Grading 2D Lookup Texture.
  41911. */
  41912. set: function (value) {
  41913. this._imageProcessingConfiguration.colorGradingTexture = value;
  41914. },
  41915. enumerable: true,
  41916. configurable: true
  41917. });
  41918. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41919. /**
  41920. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41921. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41922. * 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;
  41923. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41924. */
  41925. get: function () {
  41926. return this._imageProcessingConfiguration.colorCurves;
  41927. },
  41928. /**
  41929. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41930. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41931. * 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;
  41932. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41933. */
  41934. set: function (value) {
  41935. this._imageProcessingConfiguration.colorCurves = value;
  41936. },
  41937. enumerable: true,
  41938. configurable: true
  41939. });
  41940. StandardMaterial.prototype.getClassName = function () {
  41941. return "StandardMaterial";
  41942. };
  41943. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41944. get: function () {
  41945. return this._useLogarithmicDepth;
  41946. },
  41947. set: function (value) {
  41948. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41949. this._markAllSubMeshesAsMiscDirty();
  41950. },
  41951. enumerable: true,
  41952. configurable: true
  41953. });
  41954. StandardMaterial.prototype.needAlphaBlending = function () {
  41955. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41956. };
  41957. StandardMaterial.prototype.needAlphaTesting = function () {
  41958. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41959. };
  41960. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41961. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41962. };
  41963. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41964. return this._diffuseTexture;
  41965. };
  41966. /**
  41967. * Child classes can use it to update shaders
  41968. */
  41969. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41970. if (useInstances === void 0) { useInstances = false; }
  41971. if (subMesh.effect && this.isFrozen) {
  41972. if (this._wasPreviouslyReady && subMesh.effect) {
  41973. return true;
  41974. }
  41975. }
  41976. if (!subMesh._materialDefines) {
  41977. subMesh._materialDefines = new StandardMaterialDefines();
  41978. }
  41979. var scene = this.getScene();
  41980. var defines = subMesh._materialDefines;
  41981. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41982. if (defines._renderId === scene.getRenderId()) {
  41983. return true;
  41984. }
  41985. }
  41986. var engine = scene.getEngine();
  41987. // Lights
  41988. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41989. // Textures
  41990. if (defines._areTexturesDirty) {
  41991. defines._needUVs = false;
  41992. defines.MAINUV1 = false;
  41993. defines.MAINUV2 = false;
  41994. if (scene.texturesEnabled) {
  41995. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41996. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41997. return false;
  41998. }
  41999. else {
  42000. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42001. }
  42002. }
  42003. else {
  42004. defines.DIFFUSE = false;
  42005. }
  42006. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42007. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42008. return false;
  42009. }
  42010. else {
  42011. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42012. }
  42013. }
  42014. else {
  42015. defines.AMBIENT = false;
  42016. }
  42017. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42018. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42019. return false;
  42020. }
  42021. else {
  42022. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42023. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42024. }
  42025. }
  42026. else {
  42027. defines.OPACITY = false;
  42028. }
  42029. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42030. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42031. return false;
  42032. }
  42033. else {
  42034. defines._needNormals = true;
  42035. defines.REFLECTION = true;
  42036. defines.ROUGHNESS = (this._roughness > 0);
  42037. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42038. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42039. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42040. switch (this._reflectionTexture.coordinatesMode) {
  42041. case BABYLON.Texture.CUBIC_MODE:
  42042. case BABYLON.Texture.INVCUBIC_MODE:
  42043. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42044. break;
  42045. case BABYLON.Texture.EXPLICIT_MODE:
  42046. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42047. break;
  42048. case BABYLON.Texture.PLANAR_MODE:
  42049. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42050. break;
  42051. case BABYLON.Texture.PROJECTION_MODE:
  42052. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42053. break;
  42054. case BABYLON.Texture.SKYBOX_MODE:
  42055. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42056. break;
  42057. case BABYLON.Texture.SPHERICAL_MODE:
  42058. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42059. break;
  42060. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42061. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42062. break;
  42063. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42064. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42065. break;
  42066. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42067. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42068. break;
  42069. }
  42070. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42071. }
  42072. }
  42073. else {
  42074. defines.REFLECTION = false;
  42075. }
  42076. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42077. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42078. return false;
  42079. }
  42080. else {
  42081. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42082. }
  42083. }
  42084. else {
  42085. defines.EMISSIVE = false;
  42086. }
  42087. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42088. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42089. return false;
  42090. }
  42091. else {
  42092. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42093. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42094. }
  42095. }
  42096. else {
  42097. defines.LIGHTMAP = false;
  42098. }
  42099. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42100. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42101. return false;
  42102. }
  42103. else {
  42104. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42105. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42106. }
  42107. }
  42108. else {
  42109. defines.SPECULAR = false;
  42110. }
  42111. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42112. // Bump texure can not be not blocking.
  42113. if (!this._bumpTexture.isReady()) {
  42114. return false;
  42115. }
  42116. else {
  42117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42118. defines.PARALLAX = this._useParallax;
  42119. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42120. }
  42121. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42122. }
  42123. else {
  42124. defines.BUMP = false;
  42125. }
  42126. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42127. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42128. return false;
  42129. }
  42130. else {
  42131. defines._needUVs = true;
  42132. defines.REFRACTION = true;
  42133. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42134. }
  42135. }
  42136. else {
  42137. defines.REFRACTION = false;
  42138. }
  42139. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42140. }
  42141. else {
  42142. defines.DIFFUSE = false;
  42143. defines.AMBIENT = false;
  42144. defines.OPACITY = false;
  42145. defines.REFLECTION = false;
  42146. defines.EMISSIVE = false;
  42147. defines.LIGHTMAP = false;
  42148. defines.BUMP = false;
  42149. defines.REFRACTION = false;
  42150. }
  42151. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42152. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42153. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42154. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42155. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42156. }
  42157. if (defines._areImageProcessingDirty) {
  42158. if (!this._imageProcessingConfiguration.isReady()) {
  42159. return false;
  42160. }
  42161. this._imageProcessingConfiguration.prepareDefines(defines);
  42162. }
  42163. if (defines._areFresnelDirty) {
  42164. if (StandardMaterial.FresnelEnabled) {
  42165. // Fresnel
  42166. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42167. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42168. this._reflectionFresnelParameters) {
  42169. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42170. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42171. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42172. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42173. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42174. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42175. defines._needNormals = true;
  42176. defines.FRESNEL = true;
  42177. }
  42178. }
  42179. else {
  42180. defines.FRESNEL = false;
  42181. }
  42182. }
  42183. // Misc.
  42184. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42185. // Attribs
  42186. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42187. // Values that need to be evaluated on every frame
  42188. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42189. // Get correct effect
  42190. if (defines.isDirty) {
  42191. defines.markAsProcessed();
  42192. scene.resetCachedMaterial();
  42193. // Fallbacks
  42194. var fallbacks = new BABYLON.EffectFallbacks();
  42195. if (defines.REFLECTION) {
  42196. fallbacks.addFallback(0, "REFLECTION");
  42197. }
  42198. if (defines.SPECULAR) {
  42199. fallbacks.addFallback(0, "SPECULAR");
  42200. }
  42201. if (defines.BUMP) {
  42202. fallbacks.addFallback(0, "BUMP");
  42203. }
  42204. if (defines.PARALLAX) {
  42205. fallbacks.addFallback(1, "PARALLAX");
  42206. }
  42207. if (defines.PARALLAXOCCLUSION) {
  42208. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42209. }
  42210. if (defines.SPECULAROVERALPHA) {
  42211. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42212. }
  42213. if (defines.FOG) {
  42214. fallbacks.addFallback(1, "FOG");
  42215. }
  42216. if (defines.POINTSIZE) {
  42217. fallbacks.addFallback(0, "POINTSIZE");
  42218. }
  42219. if (defines.LOGARITHMICDEPTH) {
  42220. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42221. }
  42222. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42223. if (defines.SPECULARTERM) {
  42224. fallbacks.addFallback(0, "SPECULARTERM");
  42225. }
  42226. if (defines.DIFFUSEFRESNEL) {
  42227. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42228. }
  42229. if (defines.OPACITYFRESNEL) {
  42230. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42231. }
  42232. if (defines.REFLECTIONFRESNEL) {
  42233. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42234. }
  42235. if (defines.EMISSIVEFRESNEL) {
  42236. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42237. }
  42238. if (defines.FRESNEL) {
  42239. fallbacks.addFallback(4, "FRESNEL");
  42240. }
  42241. //Attributes
  42242. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42243. if (defines.NORMAL) {
  42244. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42245. }
  42246. if (defines.UV1) {
  42247. attribs.push(BABYLON.VertexBuffer.UVKind);
  42248. }
  42249. if (defines.UV2) {
  42250. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42251. }
  42252. if (defines.VERTEXCOLOR) {
  42253. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42254. }
  42255. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42256. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42257. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42258. var shaderName = "default";
  42259. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42260. "vFogInfos", "vFogColor", "pointSize",
  42261. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42262. "mBones",
  42263. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42264. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42265. "vReflectionPosition", "vReflectionSize",
  42266. "logarithmicDepthConstant", "vTangentSpaceParams"
  42267. ];
  42268. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42269. var uniformBuffers = ["Material", "Scene"];
  42270. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42271. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42272. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42273. uniformsNames: uniforms,
  42274. uniformBuffersNames: uniformBuffers,
  42275. samplers: samplers,
  42276. defines: defines,
  42277. maxSimultaneousLights: this._maxSimultaneousLights
  42278. });
  42279. if (this.customShaderNameResolve) {
  42280. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42281. }
  42282. var join = defines.toString();
  42283. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42284. attributes: attribs,
  42285. uniformsNames: uniforms,
  42286. uniformBuffersNames: uniformBuffers,
  42287. samplers: samplers,
  42288. defines: join,
  42289. fallbacks: fallbacks,
  42290. onCompiled: this.onCompiled,
  42291. onError: this.onError,
  42292. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42293. }, engine), defines);
  42294. this.buildUniformLayout();
  42295. }
  42296. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42297. return false;
  42298. }
  42299. defines._renderId = scene.getRenderId();
  42300. this._wasPreviouslyReady = true;
  42301. return true;
  42302. };
  42303. StandardMaterial.prototype.buildUniformLayout = function () {
  42304. // Order is important !
  42305. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42306. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42307. this._uniformBuffer.addUniform("opacityParts", 4);
  42308. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42309. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42310. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42311. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42312. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42313. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42314. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42315. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42316. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42317. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42318. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42319. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42320. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42321. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42322. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42323. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42324. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42325. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42326. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42327. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42328. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42329. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42330. this._uniformBuffer.addUniform("specularMatrix", 16);
  42331. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42332. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42333. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42334. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42335. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42336. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42337. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42338. this._uniformBuffer.addUniform("pointSize", 1);
  42339. this._uniformBuffer.create();
  42340. };
  42341. StandardMaterial.prototype.unbind = function () {
  42342. if (this._activeEffect) {
  42343. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42344. this._activeEffect.setTexture("reflection2DSampler", null);
  42345. }
  42346. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42347. this._activeEffect.setTexture("refraction2DSampler", null);
  42348. }
  42349. }
  42350. _super.prototype.unbind.call(this);
  42351. };
  42352. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42353. var scene = this.getScene();
  42354. var defines = subMesh._materialDefines;
  42355. if (!defines) {
  42356. return;
  42357. }
  42358. var effect = subMesh.effect;
  42359. if (!effect) {
  42360. return;
  42361. }
  42362. this._activeEffect = effect;
  42363. // Matrices
  42364. this.bindOnlyWorldMatrix(world);
  42365. // Normal Matrix
  42366. if (defines.OBJECTSPACE_NORMALMAP) {
  42367. world.toNormalMatrix(this._normalMatrix);
  42368. this.bindOnlyNormalMatrix(this._normalMatrix);
  42369. }
  42370. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42371. // Bones
  42372. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42373. if (mustRebind) {
  42374. this._uniformBuffer.bindToEffect(effect, "Material");
  42375. this.bindViewProjection(effect);
  42376. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42377. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42378. // Fresnel
  42379. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42380. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42381. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42382. }
  42383. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42384. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42385. }
  42386. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42387. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42388. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42389. }
  42390. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42391. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42392. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42393. }
  42394. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42395. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42396. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42397. }
  42398. }
  42399. // Textures
  42400. if (scene.texturesEnabled) {
  42401. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42402. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42403. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42404. }
  42405. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42406. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42407. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42408. }
  42409. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42410. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42411. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42412. }
  42413. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42414. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42415. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42416. if (this._reflectionTexture.boundingBoxSize) {
  42417. var cubeTexture = this._reflectionTexture;
  42418. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42419. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42420. }
  42421. }
  42422. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42423. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42424. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42425. }
  42426. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42427. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42428. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42429. }
  42430. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42431. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42432. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42433. }
  42434. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42435. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42436. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42437. if (scene._mirroredCameraPosition) {
  42438. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42439. }
  42440. else {
  42441. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42442. }
  42443. }
  42444. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42445. var depth = 1.0;
  42446. if (!this._refractionTexture.isCube) {
  42447. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42448. if (this._refractionTexture.depth) {
  42449. depth = this._refractionTexture.depth;
  42450. }
  42451. }
  42452. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42453. }
  42454. }
  42455. // Point size
  42456. if (this.pointsCloud) {
  42457. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42458. }
  42459. if (defines.SPECULARTERM) {
  42460. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42461. }
  42462. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42463. // Diffuse
  42464. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42465. }
  42466. // Textures
  42467. if (scene.texturesEnabled) {
  42468. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42469. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42470. }
  42471. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42472. effect.setTexture("ambientSampler", this._ambientTexture);
  42473. }
  42474. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42475. effect.setTexture("opacitySampler", this._opacityTexture);
  42476. }
  42477. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42478. if (this._reflectionTexture.isCube) {
  42479. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42480. }
  42481. else {
  42482. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42483. }
  42484. }
  42485. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42486. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42487. }
  42488. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42489. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42490. }
  42491. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42492. effect.setTexture("specularSampler", this._specularTexture);
  42493. }
  42494. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42495. effect.setTexture("bumpSampler", this._bumpTexture);
  42496. }
  42497. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42498. var depth = 1.0;
  42499. if (this._refractionTexture.isCube) {
  42500. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42501. }
  42502. else {
  42503. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42504. }
  42505. }
  42506. }
  42507. // Clip plane
  42508. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42509. // Colors
  42510. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42511. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42512. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42513. }
  42514. if (mustRebind || !this.isFrozen) {
  42515. // Lights
  42516. if (scene.lightsEnabled && !this._disableLighting) {
  42517. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42518. }
  42519. // View
  42520. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42521. this.bindView(effect);
  42522. }
  42523. // Fog
  42524. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42525. // Morph targets
  42526. if (defines.NUM_MORPH_INFLUENCERS) {
  42527. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42528. }
  42529. // Log. depth
  42530. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42531. // image processing
  42532. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  42533. this._imageProcessingConfiguration.bind(this._activeEffect);
  42534. }
  42535. }
  42536. this._uniformBuffer.update();
  42537. this._afterBind(mesh, this._activeEffect);
  42538. };
  42539. StandardMaterial.prototype.getAnimatables = function () {
  42540. var results = [];
  42541. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42542. results.push(this._diffuseTexture);
  42543. }
  42544. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42545. results.push(this._ambientTexture);
  42546. }
  42547. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42548. results.push(this._opacityTexture);
  42549. }
  42550. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42551. results.push(this._reflectionTexture);
  42552. }
  42553. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42554. results.push(this._emissiveTexture);
  42555. }
  42556. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42557. results.push(this._specularTexture);
  42558. }
  42559. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42560. results.push(this._bumpTexture);
  42561. }
  42562. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42563. results.push(this._lightmapTexture);
  42564. }
  42565. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42566. results.push(this._refractionTexture);
  42567. }
  42568. return results;
  42569. };
  42570. StandardMaterial.prototype.getActiveTextures = function () {
  42571. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42572. if (this._diffuseTexture) {
  42573. activeTextures.push(this._diffuseTexture);
  42574. }
  42575. if (this._ambientTexture) {
  42576. activeTextures.push(this._ambientTexture);
  42577. }
  42578. if (this._opacityTexture) {
  42579. activeTextures.push(this._opacityTexture);
  42580. }
  42581. if (this._reflectionTexture) {
  42582. activeTextures.push(this._reflectionTexture);
  42583. }
  42584. if (this._emissiveTexture) {
  42585. activeTextures.push(this._emissiveTexture);
  42586. }
  42587. if (this._specularTexture) {
  42588. activeTextures.push(this._specularTexture);
  42589. }
  42590. if (this._bumpTexture) {
  42591. activeTextures.push(this._bumpTexture);
  42592. }
  42593. if (this._lightmapTexture) {
  42594. activeTextures.push(this._lightmapTexture);
  42595. }
  42596. if (this._refractionTexture) {
  42597. activeTextures.push(this._refractionTexture);
  42598. }
  42599. return activeTextures;
  42600. };
  42601. StandardMaterial.prototype.hasTexture = function (texture) {
  42602. if (_super.prototype.hasTexture.call(this, texture)) {
  42603. return true;
  42604. }
  42605. if (this._diffuseTexture === texture) {
  42606. return true;
  42607. }
  42608. if (this._ambientTexture === texture) {
  42609. return true;
  42610. }
  42611. if (this._opacityTexture === texture) {
  42612. return true;
  42613. }
  42614. if (this._reflectionTexture === texture) {
  42615. return true;
  42616. }
  42617. if (this._emissiveTexture === texture) {
  42618. return true;
  42619. }
  42620. if (this._specularTexture === texture) {
  42621. return true;
  42622. }
  42623. if (this._bumpTexture === texture) {
  42624. return true;
  42625. }
  42626. if (this._lightmapTexture === texture) {
  42627. return true;
  42628. }
  42629. if (this._refractionTexture === texture) {
  42630. return true;
  42631. }
  42632. return false;
  42633. };
  42634. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42635. if (forceDisposeTextures) {
  42636. if (this._diffuseTexture) {
  42637. this._diffuseTexture.dispose();
  42638. }
  42639. if (this._ambientTexture) {
  42640. this._ambientTexture.dispose();
  42641. }
  42642. if (this._opacityTexture) {
  42643. this._opacityTexture.dispose();
  42644. }
  42645. if (this._reflectionTexture) {
  42646. this._reflectionTexture.dispose();
  42647. }
  42648. if (this._emissiveTexture) {
  42649. this._emissiveTexture.dispose();
  42650. }
  42651. if (this._specularTexture) {
  42652. this._specularTexture.dispose();
  42653. }
  42654. if (this._bumpTexture) {
  42655. this._bumpTexture.dispose();
  42656. }
  42657. if (this._lightmapTexture) {
  42658. this._lightmapTexture.dispose();
  42659. }
  42660. if (this._refractionTexture) {
  42661. this._refractionTexture.dispose();
  42662. }
  42663. }
  42664. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42665. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42666. }
  42667. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42668. };
  42669. StandardMaterial.prototype.clone = function (name) {
  42670. var _this = this;
  42671. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42672. result.name = name;
  42673. result.id = name;
  42674. return result;
  42675. };
  42676. StandardMaterial.prototype.serialize = function () {
  42677. return BABYLON.SerializationHelper.Serialize(this);
  42678. };
  42679. // Statics
  42680. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42681. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42682. };
  42683. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42684. get: function () {
  42685. return StandardMaterial._DiffuseTextureEnabled;
  42686. },
  42687. set: function (value) {
  42688. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42689. return;
  42690. }
  42691. StandardMaterial._DiffuseTextureEnabled = value;
  42692. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42693. },
  42694. enumerable: true,
  42695. configurable: true
  42696. });
  42697. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42698. get: function () {
  42699. return StandardMaterial._AmbientTextureEnabled;
  42700. },
  42701. set: function (value) {
  42702. if (StandardMaterial._AmbientTextureEnabled === value) {
  42703. return;
  42704. }
  42705. StandardMaterial._AmbientTextureEnabled = value;
  42706. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42707. },
  42708. enumerable: true,
  42709. configurable: true
  42710. });
  42711. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42712. get: function () {
  42713. return StandardMaterial._OpacityTextureEnabled;
  42714. },
  42715. set: function (value) {
  42716. if (StandardMaterial._OpacityTextureEnabled === value) {
  42717. return;
  42718. }
  42719. StandardMaterial._OpacityTextureEnabled = value;
  42720. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42721. },
  42722. enumerable: true,
  42723. configurable: true
  42724. });
  42725. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42726. get: function () {
  42727. return StandardMaterial._ReflectionTextureEnabled;
  42728. },
  42729. set: function (value) {
  42730. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42731. return;
  42732. }
  42733. StandardMaterial._ReflectionTextureEnabled = value;
  42734. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42735. },
  42736. enumerable: true,
  42737. configurable: true
  42738. });
  42739. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42740. get: function () {
  42741. return StandardMaterial._EmissiveTextureEnabled;
  42742. },
  42743. set: function (value) {
  42744. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42745. return;
  42746. }
  42747. StandardMaterial._EmissiveTextureEnabled = value;
  42748. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42754. get: function () {
  42755. return StandardMaterial._SpecularTextureEnabled;
  42756. },
  42757. set: function (value) {
  42758. if (StandardMaterial._SpecularTextureEnabled === value) {
  42759. return;
  42760. }
  42761. StandardMaterial._SpecularTextureEnabled = value;
  42762. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42763. },
  42764. enumerable: true,
  42765. configurable: true
  42766. });
  42767. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42768. get: function () {
  42769. return StandardMaterial._BumpTextureEnabled;
  42770. },
  42771. set: function (value) {
  42772. if (StandardMaterial._BumpTextureEnabled === value) {
  42773. return;
  42774. }
  42775. StandardMaterial._BumpTextureEnabled = value;
  42776. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42782. get: function () {
  42783. return StandardMaterial._LightmapTextureEnabled;
  42784. },
  42785. set: function (value) {
  42786. if (StandardMaterial._LightmapTextureEnabled === value) {
  42787. return;
  42788. }
  42789. StandardMaterial._LightmapTextureEnabled = value;
  42790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42796. get: function () {
  42797. return StandardMaterial._RefractionTextureEnabled;
  42798. },
  42799. set: function (value) {
  42800. if (StandardMaterial._RefractionTextureEnabled === value) {
  42801. return;
  42802. }
  42803. StandardMaterial._RefractionTextureEnabled = value;
  42804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42810. get: function () {
  42811. return StandardMaterial._ColorGradingTextureEnabled;
  42812. },
  42813. set: function (value) {
  42814. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42815. return;
  42816. }
  42817. StandardMaterial._ColorGradingTextureEnabled = value;
  42818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42824. get: function () {
  42825. return StandardMaterial._FresnelEnabled;
  42826. },
  42827. set: function (value) {
  42828. if (StandardMaterial._FresnelEnabled === value) {
  42829. return;
  42830. }
  42831. StandardMaterial._FresnelEnabled = value;
  42832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. // Flags used to enable or disable a type of texture for all Standard Materials
  42838. StandardMaterial._DiffuseTextureEnabled = true;
  42839. StandardMaterial._AmbientTextureEnabled = true;
  42840. StandardMaterial._OpacityTextureEnabled = true;
  42841. StandardMaterial._ReflectionTextureEnabled = true;
  42842. StandardMaterial._EmissiveTextureEnabled = true;
  42843. StandardMaterial._SpecularTextureEnabled = true;
  42844. StandardMaterial._BumpTextureEnabled = true;
  42845. StandardMaterial._LightmapTextureEnabled = true;
  42846. StandardMaterial._RefractionTextureEnabled = true;
  42847. StandardMaterial._ColorGradingTextureEnabled = true;
  42848. StandardMaterial._FresnelEnabled = true;
  42849. __decorate([
  42850. BABYLON.serializeAsTexture("diffuseTexture")
  42851. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42852. __decorate([
  42853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42854. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42855. __decorate([
  42856. BABYLON.serializeAsTexture("ambientTexture")
  42857. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42858. __decorate([
  42859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42860. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42861. __decorate([
  42862. BABYLON.serializeAsTexture("opacityTexture")
  42863. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42864. __decorate([
  42865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42866. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42867. __decorate([
  42868. BABYLON.serializeAsTexture("reflectionTexture")
  42869. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42870. __decorate([
  42871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42872. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42873. __decorate([
  42874. BABYLON.serializeAsTexture("emissiveTexture")
  42875. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42876. __decorate([
  42877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42878. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42879. __decorate([
  42880. BABYLON.serializeAsTexture("specularTexture")
  42881. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42882. __decorate([
  42883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42884. ], StandardMaterial.prototype, "specularTexture", void 0);
  42885. __decorate([
  42886. BABYLON.serializeAsTexture("bumpTexture")
  42887. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42888. __decorate([
  42889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42890. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42891. __decorate([
  42892. BABYLON.serializeAsTexture("lightmapTexture")
  42893. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42894. __decorate([
  42895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42896. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42897. __decorate([
  42898. BABYLON.serializeAsTexture("refractionTexture")
  42899. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42900. __decorate([
  42901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42902. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42903. __decorate([
  42904. BABYLON.serializeAsColor3("ambient")
  42905. ], StandardMaterial.prototype, "ambientColor", void 0);
  42906. __decorate([
  42907. BABYLON.serializeAsColor3("diffuse")
  42908. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42909. __decorate([
  42910. BABYLON.serializeAsColor3("specular")
  42911. ], StandardMaterial.prototype, "specularColor", void 0);
  42912. __decorate([
  42913. BABYLON.serializeAsColor3("emissive")
  42914. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42915. __decorate([
  42916. BABYLON.serialize()
  42917. ], StandardMaterial.prototype, "specularPower", void 0);
  42918. __decorate([
  42919. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42920. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42921. __decorate([
  42922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42923. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42924. __decorate([
  42925. BABYLON.serialize("useEmissiveAsIllumination")
  42926. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42927. __decorate([
  42928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42929. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42930. __decorate([
  42931. BABYLON.serialize("linkEmissiveWithDiffuse")
  42932. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42933. __decorate([
  42934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42935. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42936. __decorate([
  42937. BABYLON.serialize("useSpecularOverAlpha")
  42938. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42939. __decorate([
  42940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42941. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42942. __decorate([
  42943. BABYLON.serialize("useReflectionOverAlpha")
  42944. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42945. __decorate([
  42946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42947. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42948. __decorate([
  42949. BABYLON.serialize("disableLighting")
  42950. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42951. __decorate([
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42953. ], StandardMaterial.prototype, "disableLighting", void 0);
  42954. __decorate([
  42955. BABYLON.serialize("useObjectSpaceNormalMap")
  42956. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42957. __decorate([
  42958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42959. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42960. __decorate([
  42961. BABYLON.serialize("useParallax")
  42962. ], StandardMaterial.prototype, "_useParallax", void 0);
  42963. __decorate([
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42965. ], StandardMaterial.prototype, "useParallax", void 0);
  42966. __decorate([
  42967. BABYLON.serialize("useParallaxOcclusion")
  42968. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42969. __decorate([
  42970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42971. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42972. __decorate([
  42973. BABYLON.serialize()
  42974. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42975. __decorate([
  42976. BABYLON.serialize("roughness")
  42977. ], StandardMaterial.prototype, "_roughness", void 0);
  42978. __decorate([
  42979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42980. ], StandardMaterial.prototype, "roughness", void 0);
  42981. __decorate([
  42982. BABYLON.serialize()
  42983. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42984. __decorate([
  42985. BABYLON.serialize()
  42986. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42987. __decorate([
  42988. BABYLON.serialize("useLightmapAsShadowmap")
  42989. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42990. __decorate([
  42991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42992. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42993. __decorate([
  42994. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42995. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42996. __decorate([
  42997. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42998. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42999. __decorate([
  43000. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43001. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43002. __decorate([
  43003. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43004. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43005. __decorate([
  43006. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43007. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43008. __decorate([
  43009. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43010. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43011. __decorate([
  43012. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43013. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43014. __decorate([
  43015. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43016. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43017. __decorate([
  43018. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43019. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43020. __decorate([
  43021. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43022. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43023. __decorate([
  43024. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43025. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43026. __decorate([
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43028. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43029. __decorate([
  43030. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43031. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43032. __decorate([
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43034. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43035. __decorate([
  43036. BABYLON.serialize("maxSimultaneousLights")
  43037. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43038. __decorate([
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43040. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43041. __decorate([
  43042. BABYLON.serialize("invertNormalMapX")
  43043. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43044. __decorate([
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43047. __decorate([
  43048. BABYLON.serialize("invertNormalMapY")
  43049. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43050. __decorate([
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43052. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43053. __decorate([
  43054. BABYLON.serialize("twoSidedLighting")
  43055. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43056. __decorate([
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43059. __decorate([
  43060. BABYLON.serialize()
  43061. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43062. return StandardMaterial;
  43063. }(BABYLON.PushMaterial));
  43064. BABYLON.StandardMaterial = StandardMaterial;
  43065. })(BABYLON || (BABYLON = {}));
  43066. //# sourceMappingURL=babylon.standardMaterial.js.map
  43067. "use strict";
  43068. var BABYLON;
  43069. (function (BABYLON) {
  43070. /**
  43071. * Manages the defines for the PBR Material.
  43072. * @ignoreChildren
  43073. */
  43074. var PBRMaterialDefines = /** @class */ (function (_super) {
  43075. __extends(PBRMaterialDefines, _super);
  43076. /**
  43077. * Initializes the PBR Material defines.
  43078. */
  43079. function PBRMaterialDefines() {
  43080. var _this = _super.call(this) || this;
  43081. _this.PBR = true;
  43082. _this.MAINUV1 = false;
  43083. _this.MAINUV2 = false;
  43084. _this.UV1 = false;
  43085. _this.UV2 = false;
  43086. _this.ALBEDO = false;
  43087. _this.ALBEDODIRECTUV = 0;
  43088. _this.VERTEXCOLOR = false;
  43089. _this.AMBIENT = false;
  43090. _this.AMBIENTDIRECTUV = 0;
  43091. _this.AMBIENTINGRAYSCALE = false;
  43092. _this.OPACITY = false;
  43093. _this.VERTEXALPHA = false;
  43094. _this.OPACITYDIRECTUV = 0;
  43095. _this.OPACITYRGB = false;
  43096. _this.ALPHATEST = false;
  43097. _this.DEPTHPREPASS = false;
  43098. _this.ALPHABLEND = false;
  43099. _this.ALPHAFROMALBEDO = false;
  43100. _this.ALPHATESTVALUE = "0.5";
  43101. _this.SPECULAROVERALPHA = false;
  43102. _this.RADIANCEOVERALPHA = false;
  43103. _this.ALPHAFRESNEL = false;
  43104. _this.LINEARALPHAFRESNEL = false;
  43105. _this.PREMULTIPLYALPHA = false;
  43106. _this.EMISSIVE = false;
  43107. _this.EMISSIVEDIRECTUV = 0;
  43108. _this.REFLECTIVITY = false;
  43109. _this.REFLECTIVITYDIRECTUV = 0;
  43110. _this.SPECULARTERM = false;
  43111. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43112. _this.MICROSURFACEAUTOMATIC = false;
  43113. _this.LODBASEDMICROSFURACE = false;
  43114. _this.MICROSURFACEMAP = false;
  43115. _this.MICROSURFACEMAPDIRECTUV = 0;
  43116. _this.METALLICWORKFLOW = false;
  43117. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43118. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43119. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43120. _this.AOSTOREINMETALMAPRED = false;
  43121. _this.ENVIRONMENTBRDF = false;
  43122. _this.NORMAL = false;
  43123. _this.TANGENT = false;
  43124. _this.BUMP = false;
  43125. _this.BUMPDIRECTUV = 0;
  43126. _this.OBJECTSPACE_NORMALMAP = false;
  43127. _this.PARALLAX = false;
  43128. _this.PARALLAXOCCLUSION = false;
  43129. _this.NORMALXYSCALE = true;
  43130. _this.LIGHTMAP = false;
  43131. _this.LIGHTMAPDIRECTUV = 0;
  43132. _this.USELIGHTMAPASSHADOWMAP = false;
  43133. _this.GAMMALIGHTMAP = false;
  43134. _this.REFLECTION = false;
  43135. _this.REFLECTIONMAP_3D = false;
  43136. _this.REFLECTIONMAP_SPHERICAL = false;
  43137. _this.REFLECTIONMAP_PLANAR = false;
  43138. _this.REFLECTIONMAP_CUBIC = false;
  43139. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43140. _this.REFLECTIONMAP_PROJECTION = false;
  43141. _this.REFLECTIONMAP_SKYBOX = false;
  43142. _this.REFLECTIONMAP_EXPLICIT = false;
  43143. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43144. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43145. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43146. _this.INVERTCUBICMAP = false;
  43147. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43148. _this.USESPHERICALINVERTEX = false;
  43149. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43150. _this.LODINREFLECTIONALPHA = false;
  43151. _this.GAMMAREFLECTION = false;
  43152. _this.RADIANCEOCCLUSION = false;
  43153. _this.HORIZONOCCLUSION = false;
  43154. _this.REFRACTION = false;
  43155. _this.REFRACTIONMAP_3D = false;
  43156. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43157. _this.LODINREFRACTIONALPHA = false;
  43158. _this.GAMMAREFRACTION = false;
  43159. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43160. _this.INSTANCES = false;
  43161. _this.NUM_BONE_INFLUENCERS = 0;
  43162. _this.BonesPerMesh = 0;
  43163. _this.NONUNIFORMSCALING = false;
  43164. _this.MORPHTARGETS = false;
  43165. _this.MORPHTARGETS_NORMAL = false;
  43166. _this.MORPHTARGETS_TANGENT = false;
  43167. _this.NUM_MORPH_INFLUENCERS = 0;
  43168. _this.IMAGEPROCESSING = false;
  43169. _this.VIGNETTE = false;
  43170. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43171. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43172. _this.TONEMAPPING = false;
  43173. _this.CONTRAST = false;
  43174. _this.COLORCURVES = false;
  43175. _this.COLORGRADING = false;
  43176. _this.COLORGRADING3D = false;
  43177. _this.SAMPLER3DGREENDEPTH = false;
  43178. _this.SAMPLER3DBGRMAP = false;
  43179. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43180. _this.EXPOSURE = false;
  43181. _this.USEPHYSICALLIGHTFALLOFF = false;
  43182. _this.TWOSIDEDLIGHTING = false;
  43183. _this.SHADOWFLOAT = false;
  43184. _this.CLIPPLANE = false;
  43185. _this.POINTSIZE = false;
  43186. _this.FOG = false;
  43187. _this.LOGARITHMICDEPTH = false;
  43188. _this.FORCENORMALFORWARD = false;
  43189. _this.GEOMETRYAA = false;
  43190. _this.UNLIT = false;
  43191. _this.rebuild();
  43192. return _this;
  43193. }
  43194. /**
  43195. * Resets the PBR Material defines.
  43196. */
  43197. PBRMaterialDefines.prototype.reset = function () {
  43198. _super.prototype.reset.call(this);
  43199. this.ALPHATESTVALUE = "0.5";
  43200. this.PBR = true;
  43201. };
  43202. return PBRMaterialDefines;
  43203. }(BABYLON.MaterialDefines));
  43204. /**
  43205. * The Physically based material base class of BJS.
  43206. *
  43207. * This offers the main features of a standard PBR material.
  43208. * For more information, please refer to the documentation :
  43209. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43210. */
  43211. var PBRBaseMaterial = /** @class */ (function (_super) {
  43212. __extends(PBRBaseMaterial, _super);
  43213. /**
  43214. * Instantiates a new PBRMaterial instance.
  43215. *
  43216. * @param name The material name
  43217. * @param scene The scene the material will be use in.
  43218. */
  43219. function PBRBaseMaterial(name, scene) {
  43220. var _this = _super.call(this, name, scene) || this;
  43221. /**
  43222. * Intensity of the direct lights e.g. the four lights available in your scene.
  43223. * This impacts both the direct diffuse and specular highlights.
  43224. */
  43225. _this._directIntensity = 1.0;
  43226. /**
  43227. * Intensity of the emissive part of the material.
  43228. * This helps controlling the emissive effect without modifying the emissive color.
  43229. */
  43230. _this._emissiveIntensity = 1.0;
  43231. /**
  43232. * Intensity of the environment e.g. how much the environment will light the object
  43233. * either through harmonics for rough material or through the refelction for shiny ones.
  43234. */
  43235. _this._environmentIntensity = 1.0;
  43236. /**
  43237. * This is a special control allowing the reduction of the specular highlights coming from the
  43238. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43239. */
  43240. _this._specularIntensity = 1.0;
  43241. /**
  43242. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43243. */
  43244. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43245. /**
  43246. * Debug Control allowing disabling the bump map on this material.
  43247. */
  43248. _this._disableBumpMap = false;
  43249. /**
  43250. * AKA Occlusion Texture Intensity in other nomenclature.
  43251. */
  43252. _this._ambientTextureStrength = 1.0;
  43253. /**
  43254. * The color of a material in ambient lighting.
  43255. */
  43256. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43257. /**
  43258. * AKA Diffuse Color in other nomenclature.
  43259. */
  43260. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43261. /**
  43262. * AKA Specular Color in other nomenclature.
  43263. */
  43264. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43265. /**
  43266. * The color applied when light is reflected from a material.
  43267. */
  43268. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43269. /**
  43270. * The color applied when light is emitted from a material.
  43271. */
  43272. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43273. /**
  43274. * AKA Glossiness in other nomenclature.
  43275. */
  43276. _this._microSurface = 0.9;
  43277. /**
  43278. * source material index of refraction (IOR)' / 'destination material IOR.
  43279. */
  43280. _this._indexOfRefraction = 0.66;
  43281. /**
  43282. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43283. */
  43284. _this._invertRefractionY = false;
  43285. /**
  43286. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43287. * Materials half opaque for instance using refraction could benefit from this control.
  43288. */
  43289. _this._linkRefractionWithTransparency = false;
  43290. /**
  43291. * Specifies that the material will use the light map as a show map.
  43292. */
  43293. _this._useLightmapAsShadowmap = false;
  43294. /**
  43295. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43296. * makes the reflect vector face the model (under horizon).
  43297. */
  43298. _this._useHorizonOcclusion = true;
  43299. /**
  43300. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43301. * too much the area relying on ambient texture to define their ambient occlusion.
  43302. */
  43303. _this._useRadianceOcclusion = true;
  43304. /**
  43305. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43306. */
  43307. _this._useAlphaFromAlbedoTexture = false;
  43308. /**
  43309. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43310. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43311. */
  43312. _this._useSpecularOverAlpha = true;
  43313. /**
  43314. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43315. */
  43316. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43317. /**
  43318. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43319. */
  43320. _this._useRoughnessFromMetallicTextureAlpha = true;
  43321. /**
  43322. * Specifies if the metallic texture contains the roughness information in its green channel.
  43323. */
  43324. _this._useRoughnessFromMetallicTextureGreen = false;
  43325. /**
  43326. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43327. */
  43328. _this._useMetallnessFromMetallicTextureBlue = false;
  43329. /**
  43330. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43331. */
  43332. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43333. /**
  43334. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43335. */
  43336. _this._useAmbientInGrayScale = false;
  43337. /**
  43338. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43339. * The material will try to infer what glossiness each pixel should be.
  43340. */
  43341. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43342. /**
  43343. * BJS is using an harcoded light falloff based on a manually sets up range.
  43344. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43345. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43346. */
  43347. _this._usePhysicalLightFalloff = true;
  43348. /**
  43349. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43350. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43351. */
  43352. _this._useRadianceOverAlpha = true;
  43353. /**
  43354. * Allows using an object space normal map (instead of tangent space).
  43355. */
  43356. _this._useObjectSpaceNormalMap = false;
  43357. /**
  43358. * Allows using the bump map in parallax mode.
  43359. */
  43360. _this._useParallax = false;
  43361. /**
  43362. * Allows using the bump map in parallax occlusion mode.
  43363. */
  43364. _this._useParallaxOcclusion = false;
  43365. /**
  43366. * Controls the scale bias of the parallax mode.
  43367. */
  43368. _this._parallaxScaleBias = 0.05;
  43369. /**
  43370. * If sets to true, disables all the lights affecting the material.
  43371. */
  43372. _this._disableLighting = false;
  43373. /**
  43374. * Number of Simultaneous lights allowed on the material.
  43375. */
  43376. _this._maxSimultaneousLights = 4;
  43377. /**
  43378. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43379. */
  43380. _this._invertNormalMapX = false;
  43381. /**
  43382. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43383. */
  43384. _this._invertNormalMapY = false;
  43385. /**
  43386. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43387. */
  43388. _this._twoSidedLighting = false;
  43389. /**
  43390. * Defines the alpha limits in alpha test mode.
  43391. */
  43392. _this._alphaCutOff = 0.4;
  43393. /**
  43394. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43395. */
  43396. _this._forceAlphaTest = false;
  43397. /**
  43398. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43399. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43400. */
  43401. _this._useAlphaFresnel = false;
  43402. /**
  43403. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43404. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43405. */
  43406. _this._useLinearAlphaFresnel = false;
  43407. /**
  43408. * The transparency mode of the material.
  43409. */
  43410. _this._transparencyMode = null;
  43411. /**
  43412. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43413. * from cos thetav and roughness:
  43414. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43415. */
  43416. _this._environmentBRDFTexture = null;
  43417. /**
  43418. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43419. */
  43420. _this._forceIrradianceInFragment = false;
  43421. /**
  43422. * Force normal to face away from face.
  43423. */
  43424. _this._forceNormalForward = false;
  43425. /**
  43426. * Enables specular anti aliasing in the PBR shader.
  43427. * It will both interacts on the Geometry for analytical and IBL lighting.
  43428. * It also prefilter the roughness map based on the bump values.
  43429. */
  43430. _this._enableSpecularAntiAliasing = false;
  43431. /**
  43432. * Stores the available render targets.
  43433. */
  43434. _this._renderTargets = new BABYLON.SmartArray(16);
  43435. /**
  43436. * Sets the global ambient color for the material used in lighting calculations.
  43437. */
  43438. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43439. /**
  43440. * If set to true, no lighting calculations will be applied.
  43441. */
  43442. _this._unlit = false;
  43443. // Setup the default processing configuration to the scene.
  43444. _this._attachImageProcessingConfiguration(null);
  43445. _this.getRenderTargetTextures = function () {
  43446. _this._renderTargets.reset();
  43447. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43448. _this._renderTargets.push(_this._reflectionTexture);
  43449. }
  43450. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43451. _this._renderTargets.push(_this._refractionTexture);
  43452. }
  43453. return _this._renderTargets;
  43454. };
  43455. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43456. return _this;
  43457. }
  43458. /**
  43459. * Attaches a new image processing configuration to the PBR Material.
  43460. * @param configuration
  43461. */
  43462. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43463. var _this = this;
  43464. if (configuration === this._imageProcessingConfiguration) {
  43465. return;
  43466. }
  43467. // Detaches observer.
  43468. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43469. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43470. }
  43471. // Pick the scene configuration if needed.
  43472. if (!configuration) {
  43473. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43474. }
  43475. else {
  43476. this._imageProcessingConfiguration = configuration;
  43477. }
  43478. // Attaches observer.
  43479. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43480. _this._markAllSubMeshesAsImageProcessingDirty();
  43481. });
  43482. };
  43483. /**
  43484. * Gets the name of the material class.
  43485. */
  43486. PBRBaseMaterial.prototype.getClassName = function () {
  43487. return "PBRBaseMaterial";
  43488. };
  43489. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43490. /**
  43491. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43492. */
  43493. get: function () {
  43494. return this._useLogarithmicDepth;
  43495. },
  43496. /**
  43497. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43498. */
  43499. set: function (value) {
  43500. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43501. },
  43502. enumerable: true,
  43503. configurable: true
  43504. });
  43505. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43506. /**
  43507. * Gets the current transparency mode.
  43508. */
  43509. get: function () {
  43510. return this._transparencyMode;
  43511. },
  43512. /**
  43513. * Sets the transparency mode of the material.
  43514. */
  43515. set: function (value) {
  43516. if (this._transparencyMode === value) {
  43517. return;
  43518. }
  43519. this._transparencyMode = value;
  43520. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43521. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43522. },
  43523. enumerable: true,
  43524. configurable: true
  43525. });
  43526. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43527. /**
  43528. * Returns true if alpha blending should be disabled.
  43529. */
  43530. get: function () {
  43531. return (this._linkRefractionWithTransparency ||
  43532. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43533. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43534. },
  43535. enumerable: true,
  43536. configurable: true
  43537. });
  43538. /**
  43539. * Specifies whether or not this material should be rendered in alpha blend mode.
  43540. */
  43541. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43542. if (this._disableAlphaBlending) {
  43543. return false;
  43544. }
  43545. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43546. };
  43547. /**
  43548. * Specifies if the mesh will require alpha blending.
  43549. * @param mesh - BJS mesh.
  43550. */
  43551. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43552. if (this._disableAlphaBlending) {
  43553. return false;
  43554. }
  43555. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43556. };
  43557. /**
  43558. * Specifies whether or not this material should be rendered in alpha test mode.
  43559. */
  43560. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43561. if (this._forceAlphaTest) {
  43562. return true;
  43563. }
  43564. if (this._linkRefractionWithTransparency) {
  43565. return false;
  43566. }
  43567. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43568. };
  43569. /**
  43570. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43571. */
  43572. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43573. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43574. };
  43575. /**
  43576. * Gets the texture used for the alpha test.
  43577. */
  43578. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43579. return this._albedoTexture;
  43580. };
  43581. /**
  43582. * Specifies that the submesh is ready to be used.
  43583. * @param mesh - BJS mesh.
  43584. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43585. * @param useInstances - Specifies that instances should be used.
  43586. * @returns - boolean indicating that the submesh is ready or not.
  43587. */
  43588. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43589. if (subMesh.effect && this.isFrozen) {
  43590. if (this._wasPreviouslyReady) {
  43591. return true;
  43592. }
  43593. }
  43594. if (!subMesh._materialDefines) {
  43595. subMesh._materialDefines = new PBRMaterialDefines();
  43596. }
  43597. var defines = subMesh._materialDefines;
  43598. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43599. if (defines._renderId === this.getScene().getRenderId()) {
  43600. return true;
  43601. }
  43602. }
  43603. var scene = this.getScene();
  43604. var engine = scene.getEngine();
  43605. if (defines._areTexturesDirty) {
  43606. if (scene.texturesEnabled) {
  43607. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43608. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43609. return false;
  43610. }
  43611. }
  43612. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43613. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43614. return false;
  43615. }
  43616. }
  43617. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43618. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43619. return false;
  43620. }
  43621. }
  43622. var reflectionTexture = this._getReflectionTexture();
  43623. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43624. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43625. return false;
  43626. }
  43627. }
  43628. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43629. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43630. return false;
  43631. }
  43632. }
  43633. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43634. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43635. return false;
  43636. }
  43637. }
  43638. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43639. if (this._metallicTexture) {
  43640. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43641. return false;
  43642. }
  43643. }
  43644. else if (this._reflectivityTexture) {
  43645. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43646. return false;
  43647. }
  43648. }
  43649. if (this._microSurfaceTexture) {
  43650. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43651. return false;
  43652. }
  43653. }
  43654. }
  43655. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43656. // Bump texture cannot be not blocking.
  43657. if (!this._bumpTexture.isReady()) {
  43658. return false;
  43659. }
  43660. }
  43661. var refractionTexture = this._getRefractionTexture();
  43662. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43663. if (!refractionTexture.isReadyOrNotBlocking()) {
  43664. return false;
  43665. }
  43666. }
  43667. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43668. // This is blocking.
  43669. if (!this._environmentBRDFTexture.isReady()) {
  43670. return false;
  43671. }
  43672. }
  43673. }
  43674. }
  43675. if (defines._areImageProcessingDirty) {
  43676. if (!this._imageProcessingConfiguration.isReady()) {
  43677. return false;
  43678. }
  43679. }
  43680. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43681. mesh.createNormals(true);
  43682. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43683. }
  43684. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43685. if (effect) {
  43686. scene.resetCachedMaterial();
  43687. subMesh.setEffect(effect, defines);
  43688. this.buildUniformLayout();
  43689. }
  43690. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43691. return false;
  43692. }
  43693. defines._renderId = scene.getRenderId();
  43694. this._wasPreviouslyReady = true;
  43695. return true;
  43696. };
  43697. /**
  43698. * Specifies if the material uses metallic roughness workflow.
  43699. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43700. */
  43701. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43702. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43703. return true;
  43704. }
  43705. return false;
  43706. };
  43707. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43708. if (onCompiled === void 0) { onCompiled = null; }
  43709. if (onError === void 0) { onError = null; }
  43710. if (useInstances === void 0) { useInstances = null; }
  43711. if (useClipPlane === void 0) { useClipPlane = null; }
  43712. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43713. if (!defines.isDirty) {
  43714. return null;
  43715. }
  43716. defines.markAsProcessed();
  43717. var scene = this.getScene();
  43718. var engine = scene.getEngine();
  43719. // Fallbacks
  43720. var fallbacks = new BABYLON.EffectFallbacks();
  43721. var fallbackRank = 0;
  43722. if (defines.USESPHERICALINVERTEX) {
  43723. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43724. }
  43725. if (defines.FOG) {
  43726. fallbacks.addFallback(fallbackRank, "FOG");
  43727. }
  43728. if (defines.POINTSIZE) {
  43729. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43730. }
  43731. if (defines.LOGARITHMICDEPTH) {
  43732. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43733. }
  43734. if (defines.PARALLAX) {
  43735. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43736. }
  43737. if (defines.PARALLAXOCCLUSION) {
  43738. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43739. }
  43740. if (defines.ENVIRONMENTBRDF) {
  43741. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43742. }
  43743. if (defines.TANGENT) {
  43744. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43745. }
  43746. if (defines.BUMP) {
  43747. fallbacks.addFallback(fallbackRank++, "BUMP");
  43748. }
  43749. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43750. if (defines.SPECULARTERM) {
  43751. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43752. }
  43753. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43754. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43755. }
  43756. if (defines.LIGHTMAP) {
  43757. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43758. }
  43759. if (defines.NORMAL) {
  43760. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43761. }
  43762. if (defines.AMBIENT) {
  43763. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43764. }
  43765. if (defines.EMISSIVE) {
  43766. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43767. }
  43768. if (defines.VERTEXCOLOR) {
  43769. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43770. }
  43771. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43772. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43773. }
  43774. if (defines.MORPHTARGETS) {
  43775. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43776. }
  43777. //Attributes
  43778. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43779. if (defines.NORMAL) {
  43780. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43781. }
  43782. if (defines.TANGENT) {
  43783. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43784. }
  43785. if (defines.UV1) {
  43786. attribs.push(BABYLON.VertexBuffer.UVKind);
  43787. }
  43788. if (defines.UV2) {
  43789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43790. }
  43791. if (defines.VERTEXCOLOR) {
  43792. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43793. }
  43794. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43795. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43796. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43797. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43798. "vFogInfos", "vFogColor", "pointSize",
  43799. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43800. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43801. "mBones",
  43802. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43803. "vLightingIntensity",
  43804. "logarithmicDepthConstant",
  43805. "vSphericalX", "vSphericalY", "vSphericalZ",
  43806. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43807. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43808. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43809. "vTangentSpaceParams"
  43810. ];
  43811. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43812. "bumpSampler", "lightmapSampler", "opacitySampler",
  43813. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43814. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43815. "microSurfaceSampler", "environmentBrdfSampler"];
  43816. var uniformBuffers = ["Material", "Scene"];
  43817. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43818. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43819. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43820. uniformsNames: uniforms,
  43821. uniformBuffersNames: uniformBuffers,
  43822. samplers: samplers,
  43823. defines: defines,
  43824. maxSimultaneousLights: this._maxSimultaneousLights
  43825. });
  43826. var join = defines.toString();
  43827. return engine.createEffect("pbr", {
  43828. attributes: attribs,
  43829. uniformsNames: uniforms,
  43830. uniformBuffersNames: uniformBuffers,
  43831. samplers: samplers,
  43832. defines: join,
  43833. fallbacks: fallbacks,
  43834. onCompiled: onCompiled,
  43835. onError: onError,
  43836. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43837. }, engine);
  43838. };
  43839. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43840. if (useInstances === void 0) { useInstances = null; }
  43841. if (useClipPlane === void 0) { useClipPlane = null; }
  43842. var scene = this.getScene();
  43843. var engine = scene.getEngine();
  43844. // Lights
  43845. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43846. defines._needNormals = true;
  43847. // Textures
  43848. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43849. if (defines._areTexturesDirty) {
  43850. defines._needUVs = false;
  43851. if (scene.texturesEnabled) {
  43852. if (scene.getEngine().getCaps().textureLOD) {
  43853. defines.LODBASEDMICROSFURACE = true;
  43854. }
  43855. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43857. }
  43858. else {
  43859. defines.ALBEDO = false;
  43860. }
  43861. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43862. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43863. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43864. }
  43865. else {
  43866. defines.AMBIENT = false;
  43867. }
  43868. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43869. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43870. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43871. }
  43872. else {
  43873. defines.OPACITY = false;
  43874. }
  43875. var reflectionTexture = this._getReflectionTexture();
  43876. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43877. defines.REFLECTION = true;
  43878. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43879. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43880. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43881. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43882. defines.INVERTCUBICMAP = true;
  43883. }
  43884. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43885. switch (reflectionTexture.coordinatesMode) {
  43886. case BABYLON.Texture.CUBIC_MODE:
  43887. case BABYLON.Texture.INVCUBIC_MODE:
  43888. defines.REFLECTIONMAP_CUBIC = true;
  43889. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43890. break;
  43891. case BABYLON.Texture.EXPLICIT_MODE:
  43892. defines.REFLECTIONMAP_EXPLICIT = true;
  43893. break;
  43894. case BABYLON.Texture.PLANAR_MODE:
  43895. defines.REFLECTIONMAP_PLANAR = true;
  43896. break;
  43897. case BABYLON.Texture.PROJECTION_MODE:
  43898. defines.REFLECTIONMAP_PROJECTION = true;
  43899. break;
  43900. case BABYLON.Texture.SKYBOX_MODE:
  43901. defines.REFLECTIONMAP_SKYBOX = true;
  43902. break;
  43903. case BABYLON.Texture.SPHERICAL_MODE:
  43904. defines.REFLECTIONMAP_SPHERICAL = true;
  43905. break;
  43906. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43907. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43908. break;
  43909. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43910. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43911. break;
  43912. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43913. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43914. break;
  43915. }
  43916. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43917. if (reflectionTexture.sphericalPolynomial) {
  43918. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43919. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43920. defines.USESPHERICALINVERTEX = false;
  43921. }
  43922. else {
  43923. defines.USESPHERICALINVERTEX = true;
  43924. }
  43925. }
  43926. }
  43927. }
  43928. else {
  43929. defines.REFLECTION = false;
  43930. defines.REFLECTIONMAP_3D = false;
  43931. defines.REFLECTIONMAP_SPHERICAL = false;
  43932. defines.REFLECTIONMAP_PLANAR = false;
  43933. defines.REFLECTIONMAP_CUBIC = false;
  43934. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43935. defines.REFLECTIONMAP_PROJECTION = false;
  43936. defines.REFLECTIONMAP_SKYBOX = false;
  43937. defines.REFLECTIONMAP_EXPLICIT = false;
  43938. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43939. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43940. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43941. defines.INVERTCUBICMAP = false;
  43942. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43943. defines.USESPHERICALINVERTEX = false;
  43944. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43945. defines.LODINREFLECTIONALPHA = false;
  43946. defines.GAMMAREFLECTION = false;
  43947. }
  43948. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43949. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43950. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43951. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43952. }
  43953. else {
  43954. defines.LIGHTMAP = false;
  43955. }
  43956. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43957. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43958. }
  43959. else {
  43960. defines.EMISSIVE = false;
  43961. }
  43962. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43963. if (this._metallicTexture) {
  43964. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43965. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43966. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43967. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43968. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43969. }
  43970. else if (this._reflectivityTexture) {
  43971. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43972. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43973. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43974. }
  43975. else {
  43976. defines.REFLECTIVITY = false;
  43977. }
  43978. if (this._microSurfaceTexture) {
  43979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43980. }
  43981. else {
  43982. defines.MICROSURFACEMAP = false;
  43983. }
  43984. }
  43985. else {
  43986. defines.REFLECTIVITY = false;
  43987. defines.MICROSURFACEMAP = false;
  43988. }
  43989. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43990. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43991. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43992. defines.PARALLAX = true;
  43993. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43994. }
  43995. else {
  43996. defines.PARALLAX = false;
  43997. }
  43998. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43999. }
  44000. else {
  44001. defines.BUMP = false;
  44002. }
  44003. var refractionTexture = this._getRefractionTexture();
  44004. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44005. defines.REFRACTION = true;
  44006. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44007. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44008. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44009. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44010. if (this._linkRefractionWithTransparency) {
  44011. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44012. }
  44013. }
  44014. else {
  44015. defines.REFRACTION = false;
  44016. }
  44017. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44018. defines.ENVIRONMENTBRDF = true;
  44019. }
  44020. else {
  44021. defines.ENVIRONMENTBRDF = false;
  44022. }
  44023. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44024. defines.ALPHAFROMALBEDO = true;
  44025. }
  44026. else {
  44027. defines.ALPHAFROMALBEDO = false;
  44028. }
  44029. }
  44030. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44031. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44032. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44033. if (!this.backFaceCulling && this._twoSidedLighting) {
  44034. defines.TWOSIDEDLIGHTING = true;
  44035. }
  44036. else {
  44037. defines.TWOSIDEDLIGHTING = false;
  44038. }
  44039. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44040. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44041. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44042. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44043. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44044. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44045. }
  44046. if (defines._areImageProcessingDirty) {
  44047. this._imageProcessingConfiguration.prepareDefines(defines);
  44048. }
  44049. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44050. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44051. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44052. // Misc.
  44053. if (defines._areMiscDirty) {
  44054. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44055. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44056. }
  44057. // Values that need to be evaluated on every frame
  44058. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44059. // Attribs
  44060. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44061. };
  44062. /**
  44063. * Force shader compilation
  44064. */
  44065. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44066. var _this = this;
  44067. var localOptions = __assign({ clipPlane: false }, options);
  44068. var defines = new PBRMaterialDefines();
  44069. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44070. if (effect.isReady()) {
  44071. if (onCompiled) {
  44072. onCompiled(this);
  44073. }
  44074. }
  44075. else {
  44076. effect.onCompileObservable.add(function () {
  44077. if (onCompiled) {
  44078. onCompiled(_this);
  44079. }
  44080. });
  44081. }
  44082. };
  44083. /**
  44084. * Initializes the uniform buffer layout for the shader.
  44085. */
  44086. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44087. // Order is important !
  44088. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44089. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44090. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44091. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44092. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44093. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44094. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44095. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44096. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44097. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44098. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44099. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44100. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44101. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44102. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44103. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44104. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44105. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44106. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44107. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44108. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44109. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44110. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44111. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44112. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44113. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44114. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44115. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44116. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44117. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44118. this._uniformBuffer.addUniform("pointSize", 1);
  44119. this._uniformBuffer.create();
  44120. };
  44121. /**
  44122. * Unbinds the textures.
  44123. */
  44124. PBRBaseMaterial.prototype.unbind = function () {
  44125. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44126. this._uniformBuffer.setTexture("reflectionSampler", null);
  44127. }
  44128. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44129. this._uniformBuffer.setTexture("refractionSampler", null);
  44130. }
  44131. _super.prototype.unbind.call(this);
  44132. };
  44133. /**
  44134. * Binds the submesh data.
  44135. * @param world - The world matrix.
  44136. * @param mesh - The BJS mesh.
  44137. * @param subMesh - A submesh of the BJS mesh.
  44138. */
  44139. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44140. var scene = this.getScene();
  44141. var defines = subMesh._materialDefines;
  44142. if (!defines) {
  44143. return;
  44144. }
  44145. var effect = subMesh.effect;
  44146. if (!effect) {
  44147. return;
  44148. }
  44149. this._activeEffect = effect;
  44150. // Matrices
  44151. this.bindOnlyWorldMatrix(world);
  44152. // Normal Matrix
  44153. if (defines.OBJECTSPACE_NORMALMAP) {
  44154. world.toNormalMatrix(this._normalMatrix);
  44155. this.bindOnlyNormalMatrix(this._normalMatrix);
  44156. }
  44157. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44158. // Bones
  44159. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44160. var reflectionTexture = null;
  44161. if (mustRebind) {
  44162. this._uniformBuffer.bindToEffect(effect, "Material");
  44163. this.bindViewProjection(effect);
  44164. reflectionTexture = this._getReflectionTexture();
  44165. var refractionTexture = this._getRefractionTexture();
  44166. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44167. // Texture uniforms
  44168. if (scene.texturesEnabled) {
  44169. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44170. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44171. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44172. }
  44173. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44174. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44175. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44176. }
  44177. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44178. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44179. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44180. }
  44181. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44182. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44183. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44184. if (reflectionTexture.boundingBoxSize) {
  44185. var cubeTexture = reflectionTexture;
  44186. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44187. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44188. }
  44189. var polynomials = reflectionTexture.sphericalPolynomial;
  44190. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44191. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44192. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44193. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44194. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44195. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44196. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44197. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44198. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44199. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44200. }
  44201. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44202. }
  44203. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44204. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44205. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44206. }
  44207. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44208. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44209. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44210. }
  44211. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44212. if (this._metallicTexture) {
  44213. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44214. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44215. }
  44216. else if (this._reflectivityTexture) {
  44217. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44218. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44219. }
  44220. if (this._microSurfaceTexture) {
  44221. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44222. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44223. }
  44224. }
  44225. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44226. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44227. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44228. if (scene._mirroredCameraPosition) {
  44229. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44230. }
  44231. else {
  44232. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44233. }
  44234. }
  44235. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44236. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44237. var depth = 1.0;
  44238. if (!refractionTexture.isCube) {
  44239. if (refractionTexture.depth) {
  44240. depth = refractionTexture.depth;
  44241. }
  44242. }
  44243. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44244. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44245. }
  44246. }
  44247. // Point size
  44248. if (this.pointsCloud) {
  44249. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44250. }
  44251. // Colors
  44252. if (defines.METALLICWORKFLOW) {
  44253. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44254. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44255. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44256. }
  44257. else {
  44258. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44259. }
  44260. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44261. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44262. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44263. // Misc
  44264. this._lightingInfos.x = this._directIntensity;
  44265. this._lightingInfos.y = this._emissiveIntensity;
  44266. this._lightingInfos.z = this._environmentIntensity;
  44267. this._lightingInfos.w = this._specularIntensity;
  44268. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44269. }
  44270. // Textures
  44271. if (scene.texturesEnabled) {
  44272. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44273. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44274. }
  44275. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44276. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44277. }
  44278. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44279. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44280. }
  44281. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44282. if (defines.LODBASEDMICROSFURACE) {
  44283. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44284. }
  44285. else {
  44286. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44287. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44288. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44289. }
  44290. }
  44291. if (defines.ENVIRONMENTBRDF) {
  44292. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44293. }
  44294. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44295. if (defines.LODBASEDMICROSFURACE) {
  44296. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44297. }
  44298. else {
  44299. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44300. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44301. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44302. }
  44303. }
  44304. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44305. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44306. }
  44307. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44308. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44309. }
  44310. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44311. if (this._metallicTexture) {
  44312. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44313. }
  44314. else if (this._reflectivityTexture) {
  44315. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44316. }
  44317. if (this._microSurfaceTexture) {
  44318. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44319. }
  44320. }
  44321. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44322. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44323. }
  44324. }
  44325. // Clip plane
  44326. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44327. // Colors
  44328. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44329. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44330. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44331. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44332. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44333. }
  44334. if (mustRebind || !this.isFrozen) {
  44335. // Lights
  44336. if (scene.lightsEnabled && !this._disableLighting) {
  44337. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44338. }
  44339. // View
  44340. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44341. this.bindView(effect);
  44342. }
  44343. // Fog
  44344. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44345. // Morph targets
  44346. if (defines.NUM_MORPH_INFLUENCERS) {
  44347. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44348. }
  44349. // image processing
  44350. this._imageProcessingConfiguration.bind(this._activeEffect);
  44351. // Log. depth
  44352. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44353. }
  44354. this._uniformBuffer.update();
  44355. this._afterBind(mesh);
  44356. };
  44357. /**
  44358. * Returns the animatable textures.
  44359. * @returns - Array of animatable textures.
  44360. */
  44361. PBRBaseMaterial.prototype.getAnimatables = function () {
  44362. var results = [];
  44363. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44364. results.push(this._albedoTexture);
  44365. }
  44366. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44367. results.push(this._ambientTexture);
  44368. }
  44369. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44370. results.push(this._opacityTexture);
  44371. }
  44372. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44373. results.push(this._reflectionTexture);
  44374. }
  44375. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44376. results.push(this._emissiveTexture);
  44377. }
  44378. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44379. results.push(this._metallicTexture);
  44380. }
  44381. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44382. results.push(this._reflectivityTexture);
  44383. }
  44384. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44385. results.push(this._bumpTexture);
  44386. }
  44387. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44388. results.push(this._lightmapTexture);
  44389. }
  44390. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44391. results.push(this._refractionTexture);
  44392. }
  44393. return results;
  44394. };
  44395. /**
  44396. * Returns the texture used for reflections.
  44397. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44398. */
  44399. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44400. if (this._reflectionTexture) {
  44401. return this._reflectionTexture;
  44402. }
  44403. return this.getScene().environmentTexture;
  44404. };
  44405. /**
  44406. * Returns the texture used for refraction or null if none is used.
  44407. * @returns - Refection texture if present. If no refraction texture and refraction
  44408. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44409. */
  44410. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44411. if (this._refractionTexture) {
  44412. return this._refractionTexture;
  44413. }
  44414. if (this._linkRefractionWithTransparency) {
  44415. return this.getScene().environmentTexture;
  44416. }
  44417. return null;
  44418. };
  44419. /**
  44420. * Disposes the resources of the material.
  44421. * @param forceDisposeEffect - Forces the disposal of effects.
  44422. * @param forceDisposeTextures - Forces the disposal of all textures.
  44423. */
  44424. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44425. if (forceDisposeTextures) {
  44426. if (this._albedoTexture) {
  44427. this._albedoTexture.dispose();
  44428. }
  44429. if (this._ambientTexture) {
  44430. this._ambientTexture.dispose();
  44431. }
  44432. if (this._opacityTexture) {
  44433. this._opacityTexture.dispose();
  44434. }
  44435. if (this._reflectionTexture) {
  44436. this._reflectionTexture.dispose();
  44437. }
  44438. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44439. this._environmentBRDFTexture.dispose();
  44440. }
  44441. if (this._emissiveTexture) {
  44442. this._emissiveTexture.dispose();
  44443. }
  44444. if (this._metallicTexture) {
  44445. this._metallicTexture.dispose();
  44446. }
  44447. if (this._reflectivityTexture) {
  44448. this._reflectivityTexture.dispose();
  44449. }
  44450. if (this._bumpTexture) {
  44451. this._bumpTexture.dispose();
  44452. }
  44453. if (this._lightmapTexture) {
  44454. this._lightmapTexture.dispose();
  44455. }
  44456. if (this._refractionTexture) {
  44457. this._refractionTexture.dispose();
  44458. }
  44459. }
  44460. this._renderTargets.dispose();
  44461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44463. }
  44464. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44465. };
  44466. /**
  44467. * Stores the reflectivity values based on metallic roughness workflow.
  44468. */
  44469. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44470. __decorate([
  44471. BABYLON.serializeAsImageProcessingConfiguration()
  44472. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44473. __decorate([
  44474. BABYLON.serialize()
  44475. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44476. __decorate([
  44477. BABYLON.serialize()
  44478. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44479. return PBRBaseMaterial;
  44480. }(BABYLON.PushMaterial));
  44481. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44482. })(BABYLON || (BABYLON = {}));
  44483. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44484. "use strict";
  44485. var BABYLON;
  44486. (function (BABYLON) {
  44487. /**
  44488. * The Physically based simple base material of BJS.
  44489. *
  44490. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44491. * It is used as the base class for both the specGloss and metalRough conventions.
  44492. */
  44493. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44494. __extends(PBRBaseSimpleMaterial, _super);
  44495. /**
  44496. * Instantiates a new PBRMaterial instance.
  44497. *
  44498. * @param name The material name
  44499. * @param scene The scene the material will be use in.
  44500. */
  44501. function PBRBaseSimpleMaterial(name, scene) {
  44502. var _this = _super.call(this, name, scene) || this;
  44503. /**
  44504. * Number of Simultaneous lights allowed on the material.
  44505. */
  44506. _this.maxSimultaneousLights = 4;
  44507. /**
  44508. * If sets to true, disables all the lights affecting the material.
  44509. */
  44510. _this.disableLighting = false;
  44511. /**
  44512. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44513. */
  44514. _this.invertNormalMapX = false;
  44515. /**
  44516. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44517. */
  44518. _this.invertNormalMapY = false;
  44519. /**
  44520. * Emissivie color used to self-illuminate the model.
  44521. */
  44522. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44523. /**
  44524. * Occlusion Channel Strenght.
  44525. */
  44526. _this.occlusionStrength = 1.0;
  44527. _this.useLightmapAsShadowmap = false;
  44528. _this._useAlphaFromAlbedoTexture = true;
  44529. _this._useAmbientInGrayScale = true;
  44530. return _this;
  44531. }
  44532. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44533. /**
  44534. * Gets the current double sided mode.
  44535. */
  44536. get: function () {
  44537. return this._twoSidedLighting;
  44538. },
  44539. /**
  44540. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44541. */
  44542. set: function (value) {
  44543. if (this._twoSidedLighting === value) {
  44544. return;
  44545. }
  44546. this._twoSidedLighting = value;
  44547. this.backFaceCulling = !value;
  44548. this._markAllSubMeshesAsTexturesDirty();
  44549. },
  44550. enumerable: true,
  44551. configurable: true
  44552. });
  44553. /**
  44554. * Return the active textures of the material.
  44555. */
  44556. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44557. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44558. if (this.environmentTexture) {
  44559. activeTextures.push(this.environmentTexture);
  44560. }
  44561. if (this.normalTexture) {
  44562. activeTextures.push(this.normalTexture);
  44563. }
  44564. if (this.emissiveTexture) {
  44565. activeTextures.push(this.emissiveTexture);
  44566. }
  44567. if (this.occlusionTexture) {
  44568. activeTextures.push(this.occlusionTexture);
  44569. }
  44570. if (this.lightmapTexture) {
  44571. activeTextures.push(this.lightmapTexture);
  44572. }
  44573. return activeTextures;
  44574. };
  44575. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44576. if (_super.prototype.hasTexture.call(this, texture)) {
  44577. return true;
  44578. }
  44579. if (this.lightmapTexture === texture) {
  44580. return true;
  44581. }
  44582. return false;
  44583. };
  44584. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44585. return "PBRBaseSimpleMaterial";
  44586. };
  44587. __decorate([
  44588. BABYLON.serialize(),
  44589. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44590. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44591. __decorate([
  44592. BABYLON.serialize(),
  44593. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44594. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44595. __decorate([
  44596. BABYLON.serializeAsTexture(),
  44597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44598. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44599. __decorate([
  44600. BABYLON.serialize(),
  44601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44602. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44603. __decorate([
  44604. BABYLON.serialize(),
  44605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44606. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44607. __decorate([
  44608. BABYLON.serializeAsTexture(),
  44609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44610. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44611. __decorate([
  44612. BABYLON.serializeAsColor3("emissive"),
  44613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44614. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44615. __decorate([
  44616. BABYLON.serializeAsTexture(),
  44617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44618. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44619. __decorate([
  44620. BABYLON.serialize(),
  44621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44622. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44623. __decorate([
  44624. BABYLON.serializeAsTexture(),
  44625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44626. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44627. __decorate([
  44628. BABYLON.serialize(),
  44629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44630. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44631. __decorate([
  44632. BABYLON.serialize()
  44633. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44634. __decorate([
  44635. BABYLON.serializeAsTexture(),
  44636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44637. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44638. __decorate([
  44639. BABYLON.serialize(),
  44640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44641. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44642. return PBRBaseSimpleMaterial;
  44643. }(BABYLON.PBRBaseMaterial));
  44644. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44645. })(BABYLON || (BABYLON = {}));
  44646. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44647. "use strict";
  44648. var BABYLON;
  44649. (function (BABYLON) {
  44650. /**
  44651. * The Physically based material of BJS.
  44652. *
  44653. * This offers the main features of a standard PBR material.
  44654. * For more information, please refer to the documentation :
  44655. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44656. */
  44657. var PBRMaterial = /** @class */ (function (_super) {
  44658. __extends(PBRMaterial, _super);
  44659. /**
  44660. * Instantiates a new PBRMaterial instance.
  44661. *
  44662. * @param name The material name
  44663. * @param scene The scene the material will be use in.
  44664. */
  44665. function PBRMaterial(name, scene) {
  44666. var _this = _super.call(this, name, scene) || this;
  44667. /**
  44668. * Intensity of the direct lights e.g. the four lights available in your scene.
  44669. * This impacts both the direct diffuse and specular highlights.
  44670. */
  44671. _this.directIntensity = 1.0;
  44672. /**
  44673. * Intensity of the emissive part of the material.
  44674. * This helps controlling the emissive effect without modifying the emissive color.
  44675. */
  44676. _this.emissiveIntensity = 1.0;
  44677. /**
  44678. * Intensity of the environment e.g. how much the environment will light the object
  44679. * either through harmonics for rough material or through the refelction for shiny ones.
  44680. */
  44681. _this.environmentIntensity = 1.0;
  44682. /**
  44683. * This is a special control allowing the reduction of the specular highlights coming from the
  44684. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44685. */
  44686. _this.specularIntensity = 1.0;
  44687. /**
  44688. * Debug Control allowing disabling the bump map on this material.
  44689. */
  44690. _this.disableBumpMap = false;
  44691. /**
  44692. * AKA Occlusion Texture Intensity in other nomenclature.
  44693. */
  44694. _this.ambientTextureStrength = 1.0;
  44695. /**
  44696. * The color of a material in ambient lighting.
  44697. */
  44698. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44699. /**
  44700. * AKA Diffuse Color in other nomenclature.
  44701. */
  44702. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44703. /**
  44704. * AKA Specular Color in other nomenclature.
  44705. */
  44706. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44707. /**
  44708. * The color reflected from the material.
  44709. */
  44710. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44711. /**
  44712. * The color emitted from the material.
  44713. */
  44714. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44715. /**
  44716. * AKA Glossiness in other nomenclature.
  44717. */
  44718. _this.microSurface = 1.0;
  44719. /**
  44720. * source material index of refraction (IOR)' / 'destination material IOR.
  44721. */
  44722. _this.indexOfRefraction = 0.66;
  44723. /**
  44724. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44725. */
  44726. _this.invertRefractionY = false;
  44727. /**
  44728. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44729. * Materials half opaque for instance using refraction could benefit from this control.
  44730. */
  44731. _this.linkRefractionWithTransparency = false;
  44732. _this.useLightmapAsShadowmap = false;
  44733. /**
  44734. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44735. */
  44736. _this.useAlphaFromAlbedoTexture = false;
  44737. /**
  44738. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44739. */
  44740. _this.forceAlphaTest = false;
  44741. /**
  44742. * Defines the alpha limits in alpha test mode.
  44743. */
  44744. _this.alphaCutOff = 0.4;
  44745. /**
  44746. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44747. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44748. */
  44749. _this.useSpecularOverAlpha = true;
  44750. /**
  44751. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44752. */
  44753. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44754. /**
  44755. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44756. */
  44757. _this.useRoughnessFromMetallicTextureAlpha = true;
  44758. /**
  44759. * Specifies if the metallic texture contains the roughness information in its green channel.
  44760. */
  44761. _this.useRoughnessFromMetallicTextureGreen = false;
  44762. /**
  44763. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44764. */
  44765. _this.useMetallnessFromMetallicTextureBlue = false;
  44766. /**
  44767. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44768. */
  44769. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44770. /**
  44771. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44772. */
  44773. _this.useAmbientInGrayScale = false;
  44774. /**
  44775. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44776. * The material will try to infer what glossiness each pixel should be.
  44777. */
  44778. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44779. /**
  44780. * BJS is using an harcoded light falloff based on a manually sets up range.
  44781. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44782. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44783. */
  44784. _this.usePhysicalLightFalloff = true;
  44785. /**
  44786. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44787. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44788. */
  44789. _this.useRadianceOverAlpha = true;
  44790. /**
  44791. * Allows using an object space normal map (instead of tangent space).
  44792. */
  44793. _this.useObjectSpaceNormalMap = false;
  44794. /**
  44795. * Allows using the bump map in parallax mode.
  44796. */
  44797. _this.useParallax = false;
  44798. /**
  44799. * Allows using the bump map in parallax occlusion mode.
  44800. */
  44801. _this.useParallaxOcclusion = false;
  44802. /**
  44803. * Controls the scale bias of the parallax mode.
  44804. */
  44805. _this.parallaxScaleBias = 0.05;
  44806. /**
  44807. * If sets to true, disables all the lights affecting the material.
  44808. */
  44809. _this.disableLighting = false;
  44810. /**
  44811. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44812. */
  44813. _this.forceIrradianceInFragment = false;
  44814. /**
  44815. * Number of Simultaneous lights allowed on the material.
  44816. */
  44817. _this.maxSimultaneousLights = 4;
  44818. /**
  44819. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44820. */
  44821. _this.invertNormalMapX = false;
  44822. /**
  44823. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44824. */
  44825. _this.invertNormalMapY = false;
  44826. /**
  44827. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44828. */
  44829. _this.twoSidedLighting = false;
  44830. /**
  44831. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44832. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44833. */
  44834. _this.useAlphaFresnel = false;
  44835. /**
  44836. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44837. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44838. */
  44839. _this.useLinearAlphaFresnel = false;
  44840. /**
  44841. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44842. * And/Or occlude the blended part.
  44843. */
  44844. _this.environmentBRDFTexture = null;
  44845. /**
  44846. * Force normal to face away from face.
  44847. */
  44848. _this.forceNormalForward = false;
  44849. /**
  44850. * Enables specular anti aliasing in the PBR shader.
  44851. * It will both interacts on the Geometry for analytical and IBL lighting.
  44852. * It also prefilter the roughness map based on the bump values.
  44853. */
  44854. _this.enableSpecularAntiAliasing = false;
  44855. /**
  44856. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44857. * makes the reflect vector face the model (under horizon).
  44858. */
  44859. _this.useHorizonOcclusion = true;
  44860. /**
  44861. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44862. * too much the area relying on ambient texture to define their ambient occlusion.
  44863. */
  44864. _this.useRadianceOcclusion = true;
  44865. /**
  44866. * If set to true, no lighting calculations will be applied.
  44867. */
  44868. _this.unlit = false;
  44869. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44870. return _this;
  44871. }
  44872. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44873. /**
  44874. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44875. */
  44876. get: function () {
  44877. return this._PBRMATERIAL_OPAQUE;
  44878. },
  44879. enumerable: true,
  44880. configurable: true
  44881. });
  44882. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44883. /**
  44884. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44885. */
  44886. get: function () {
  44887. return this._PBRMATERIAL_ALPHATEST;
  44888. },
  44889. enumerable: true,
  44890. configurable: true
  44891. });
  44892. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44893. /**
  44894. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44895. */
  44896. get: function () {
  44897. return this._PBRMATERIAL_ALPHABLEND;
  44898. },
  44899. enumerable: true,
  44900. configurable: true
  44901. });
  44902. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44903. /**
  44904. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44905. * They are also discarded below the alpha cutoff threshold to improve performances.
  44906. */
  44907. get: function () {
  44908. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44909. },
  44910. enumerable: true,
  44911. configurable: true
  44912. });
  44913. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44914. /**
  44915. * Gets the image processing configuration used either in this material.
  44916. */
  44917. get: function () {
  44918. return this._imageProcessingConfiguration;
  44919. },
  44920. /**
  44921. * Sets the Default image processing configuration used either in the this material.
  44922. *
  44923. * If sets to null, the scene one is in use.
  44924. */
  44925. set: function (value) {
  44926. this._attachImageProcessingConfiguration(value);
  44927. // Ensure the effect will be rebuilt.
  44928. this._markAllSubMeshesAsTexturesDirty();
  44929. },
  44930. enumerable: true,
  44931. configurable: true
  44932. });
  44933. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44934. /**
  44935. * Gets wether the color curves effect is enabled.
  44936. */
  44937. get: function () {
  44938. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44939. },
  44940. /**
  44941. * Sets wether the color curves effect is enabled.
  44942. */
  44943. set: function (value) {
  44944. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44945. },
  44946. enumerable: true,
  44947. configurable: true
  44948. });
  44949. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44950. /**
  44951. * Gets wether the color grading effect is enabled.
  44952. */
  44953. get: function () {
  44954. return this.imageProcessingConfiguration.colorGradingEnabled;
  44955. },
  44956. /**
  44957. * Gets wether the color grading effect is enabled.
  44958. */
  44959. set: function (value) {
  44960. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44961. },
  44962. enumerable: true,
  44963. configurable: true
  44964. });
  44965. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44966. /**
  44967. * Gets wether tonemapping is enabled or not.
  44968. */
  44969. get: function () {
  44970. return this._imageProcessingConfiguration.toneMappingEnabled;
  44971. },
  44972. /**
  44973. * Sets wether tonemapping is enabled or not
  44974. */
  44975. set: function (value) {
  44976. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44977. },
  44978. enumerable: true,
  44979. configurable: true
  44980. });
  44981. ;
  44982. ;
  44983. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44984. /**
  44985. * The camera exposure used on this material.
  44986. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44987. * This corresponds to a photographic exposure.
  44988. */
  44989. get: function () {
  44990. return this._imageProcessingConfiguration.exposure;
  44991. },
  44992. /**
  44993. * The camera exposure used on this material.
  44994. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44995. * This corresponds to a photographic exposure.
  44996. */
  44997. set: function (value) {
  44998. this._imageProcessingConfiguration.exposure = value;
  44999. },
  45000. enumerable: true,
  45001. configurable: true
  45002. });
  45003. ;
  45004. ;
  45005. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45006. /**
  45007. * Gets The camera contrast used on this material.
  45008. */
  45009. get: function () {
  45010. return this._imageProcessingConfiguration.contrast;
  45011. },
  45012. /**
  45013. * Sets The camera contrast used on this material.
  45014. */
  45015. set: function (value) {
  45016. this._imageProcessingConfiguration.contrast = value;
  45017. },
  45018. enumerable: true,
  45019. configurable: true
  45020. });
  45021. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45022. /**
  45023. * Gets the Color Grading 2D Lookup Texture.
  45024. */
  45025. get: function () {
  45026. return this._imageProcessingConfiguration.colorGradingTexture;
  45027. },
  45028. /**
  45029. * Sets the Color Grading 2D Lookup Texture.
  45030. */
  45031. set: function (value) {
  45032. this._imageProcessingConfiguration.colorGradingTexture = value;
  45033. },
  45034. enumerable: true,
  45035. configurable: true
  45036. });
  45037. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45038. /**
  45039. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45040. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45041. * 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;
  45042. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45043. */
  45044. get: function () {
  45045. return this._imageProcessingConfiguration.colorCurves;
  45046. },
  45047. /**
  45048. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45049. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45050. * 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;
  45051. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45052. */
  45053. set: function (value) {
  45054. this._imageProcessingConfiguration.colorCurves = value;
  45055. },
  45056. enumerable: true,
  45057. configurable: true
  45058. });
  45059. /**
  45060. * Returns the name of this material class.
  45061. */
  45062. PBRMaterial.prototype.getClassName = function () {
  45063. return "PBRMaterial";
  45064. };
  45065. /**
  45066. * Returns an array of the actively used textures.
  45067. * @returns - Array of BaseTextures
  45068. */
  45069. PBRMaterial.prototype.getActiveTextures = function () {
  45070. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45071. if (this._albedoTexture) {
  45072. activeTextures.push(this._albedoTexture);
  45073. }
  45074. if (this._ambientTexture) {
  45075. activeTextures.push(this._ambientTexture);
  45076. }
  45077. if (this._opacityTexture) {
  45078. activeTextures.push(this._opacityTexture);
  45079. }
  45080. if (this._reflectionTexture) {
  45081. activeTextures.push(this._reflectionTexture);
  45082. }
  45083. if (this._emissiveTexture) {
  45084. activeTextures.push(this._emissiveTexture);
  45085. }
  45086. if (this._reflectivityTexture) {
  45087. activeTextures.push(this._reflectivityTexture);
  45088. }
  45089. if (this._metallicTexture) {
  45090. activeTextures.push(this._metallicTexture);
  45091. }
  45092. if (this._microSurfaceTexture) {
  45093. activeTextures.push(this._microSurfaceTexture);
  45094. }
  45095. if (this._bumpTexture) {
  45096. activeTextures.push(this._bumpTexture);
  45097. }
  45098. if (this._lightmapTexture) {
  45099. activeTextures.push(this._lightmapTexture);
  45100. }
  45101. if (this._refractionTexture) {
  45102. activeTextures.push(this._refractionTexture);
  45103. }
  45104. return activeTextures;
  45105. };
  45106. /**
  45107. * Checks to see if a texture is used in the material.
  45108. * @param texture - Base texture to use.
  45109. * @returns - Boolean specifying if a texture is used in the material.
  45110. */
  45111. PBRMaterial.prototype.hasTexture = function (texture) {
  45112. if (_super.prototype.hasTexture.call(this, texture)) {
  45113. return true;
  45114. }
  45115. if (this._albedoTexture === texture) {
  45116. return true;
  45117. }
  45118. if (this._ambientTexture === texture) {
  45119. return true;
  45120. }
  45121. if (this._opacityTexture === texture) {
  45122. return true;
  45123. }
  45124. if (this._reflectionTexture === texture) {
  45125. return true;
  45126. }
  45127. if (this._reflectivityTexture === texture) {
  45128. return true;
  45129. }
  45130. if (this._metallicTexture === texture) {
  45131. return true;
  45132. }
  45133. if (this._microSurfaceTexture === texture) {
  45134. return true;
  45135. }
  45136. if (this._bumpTexture === texture) {
  45137. return true;
  45138. }
  45139. if (this._lightmapTexture === texture) {
  45140. return true;
  45141. }
  45142. if (this._refractionTexture === texture) {
  45143. return true;
  45144. }
  45145. return false;
  45146. };
  45147. /**
  45148. * Makes a duplicate of the current material.
  45149. * @param name - name to use for the new material.
  45150. */
  45151. PBRMaterial.prototype.clone = function (name) {
  45152. var _this = this;
  45153. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45154. clone.id = name;
  45155. clone.name = name;
  45156. return clone;
  45157. };
  45158. /**
  45159. * Serializes this PBR Material.
  45160. * @returns - An object with the serialized material.
  45161. */
  45162. PBRMaterial.prototype.serialize = function () {
  45163. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45164. serializationObject.customType = "BABYLON.PBRMaterial";
  45165. return serializationObject;
  45166. };
  45167. // Statics
  45168. /**
  45169. * Parses a PBR Material from a serialized object.
  45170. * @param source - Serialized object.
  45171. * @param scene - BJS scene instance.
  45172. * @param rootUrl - url for the scene object
  45173. * @returns - PBRMaterial
  45174. */
  45175. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45176. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45177. };
  45178. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45179. /**
  45180. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45181. */
  45182. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45183. /**
  45184. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45185. */
  45186. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45187. /**
  45188. * 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.
  45189. * They are also discarded below the alpha cutoff threshold to improve performances.
  45190. */
  45191. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45192. __decorate([
  45193. BABYLON.serialize(),
  45194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45195. ], PBRMaterial.prototype, "directIntensity", void 0);
  45196. __decorate([
  45197. BABYLON.serialize(),
  45198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45199. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45200. __decorate([
  45201. BABYLON.serialize(),
  45202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45203. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45204. __decorate([
  45205. BABYLON.serialize(),
  45206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45207. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45208. __decorate([
  45209. BABYLON.serialize(),
  45210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45211. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45212. __decorate([
  45213. BABYLON.serializeAsTexture(),
  45214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45215. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45216. __decorate([
  45217. BABYLON.serializeAsTexture(),
  45218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45219. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45220. __decorate([
  45221. BABYLON.serialize(),
  45222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45223. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45224. __decorate([
  45225. BABYLON.serializeAsTexture(),
  45226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45227. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45228. __decorate([
  45229. BABYLON.serializeAsTexture(),
  45230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45231. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45232. __decorate([
  45233. BABYLON.serializeAsTexture(),
  45234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45235. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45236. __decorate([
  45237. BABYLON.serializeAsTexture(),
  45238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45239. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45240. __decorate([
  45241. BABYLON.serializeAsTexture(),
  45242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45243. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45244. __decorate([
  45245. BABYLON.serialize(),
  45246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45247. ], PBRMaterial.prototype, "metallic", void 0);
  45248. __decorate([
  45249. BABYLON.serialize(),
  45250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45251. ], PBRMaterial.prototype, "roughness", void 0);
  45252. __decorate([
  45253. BABYLON.serializeAsTexture(),
  45254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45255. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45256. __decorate([
  45257. BABYLON.serializeAsTexture(),
  45258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45259. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45260. __decorate([
  45261. BABYLON.serializeAsTexture(),
  45262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45263. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45264. __decorate([
  45265. BABYLON.serializeAsTexture(),
  45266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45267. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45268. __decorate([
  45269. BABYLON.serializeAsColor3("ambient"),
  45270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45271. ], PBRMaterial.prototype, "ambientColor", void 0);
  45272. __decorate([
  45273. BABYLON.serializeAsColor3("albedo"),
  45274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45275. ], PBRMaterial.prototype, "albedoColor", void 0);
  45276. __decorate([
  45277. BABYLON.serializeAsColor3("reflectivity"),
  45278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45279. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45280. __decorate([
  45281. BABYLON.serializeAsColor3("reflection"),
  45282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45283. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45284. __decorate([
  45285. BABYLON.serializeAsColor3("emissive"),
  45286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45287. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45288. __decorate([
  45289. BABYLON.serialize(),
  45290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45291. ], PBRMaterial.prototype, "microSurface", void 0);
  45292. __decorate([
  45293. BABYLON.serialize(),
  45294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45295. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45296. __decorate([
  45297. BABYLON.serialize(),
  45298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45299. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45300. __decorate([
  45301. BABYLON.serialize(),
  45302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45303. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45304. __decorate([
  45305. BABYLON.serialize(),
  45306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45307. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45308. __decorate([
  45309. BABYLON.serialize(),
  45310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45311. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45312. __decorate([
  45313. BABYLON.serialize(),
  45314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45315. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45316. __decorate([
  45317. BABYLON.serialize(),
  45318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45319. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45320. __decorate([
  45321. BABYLON.serialize(),
  45322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45323. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45324. __decorate([
  45325. BABYLON.serialize(),
  45326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45327. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45328. __decorate([
  45329. BABYLON.serialize(),
  45330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45331. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45332. __decorate([
  45333. BABYLON.serialize(),
  45334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45335. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45336. __decorate([
  45337. BABYLON.serialize(),
  45338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45339. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45340. __decorate([
  45341. BABYLON.serialize(),
  45342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45343. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45344. __decorate([
  45345. BABYLON.serialize(),
  45346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45347. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45348. __decorate([
  45349. BABYLON.serialize(),
  45350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45351. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45352. __decorate([
  45353. BABYLON.serialize(),
  45354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45355. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45356. __decorate([
  45357. BABYLON.serialize(),
  45358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45359. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45360. __decorate([
  45361. BABYLON.serialize(),
  45362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45363. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45364. __decorate([
  45365. BABYLON.serialize(),
  45366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45367. ], PBRMaterial.prototype, "useParallax", void 0);
  45368. __decorate([
  45369. BABYLON.serialize(),
  45370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45371. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45372. __decorate([
  45373. BABYLON.serialize(),
  45374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45375. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45376. __decorate([
  45377. BABYLON.serialize(),
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45379. ], PBRMaterial.prototype, "disableLighting", void 0);
  45380. __decorate([
  45381. BABYLON.serialize(),
  45382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45383. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45384. __decorate([
  45385. BABYLON.serialize(),
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45387. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45388. __decorate([
  45389. BABYLON.serialize(),
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45391. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45392. __decorate([
  45393. BABYLON.serialize(),
  45394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45395. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45396. __decorate([
  45397. BABYLON.serialize(),
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45399. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45400. __decorate([
  45401. BABYLON.serialize(),
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45403. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45404. __decorate([
  45405. BABYLON.serialize(),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45407. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45408. __decorate([
  45409. BABYLON.serializeAsTexture(),
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45411. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45412. __decorate([
  45413. BABYLON.serialize(),
  45414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45415. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45416. __decorate([
  45417. BABYLON.serialize(),
  45418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45419. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45420. __decorate([
  45421. BABYLON.serialize(),
  45422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45423. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45424. __decorate([
  45425. BABYLON.serialize(),
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45427. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45428. __decorate([
  45429. BABYLON.serialize(),
  45430. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45431. ], PBRMaterial.prototype, "unlit", void 0);
  45432. return PBRMaterial;
  45433. }(BABYLON.PBRBaseMaterial));
  45434. BABYLON.PBRMaterial = PBRMaterial;
  45435. })(BABYLON || (BABYLON = {}));
  45436. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45437. "use strict";
  45438. var BABYLON;
  45439. (function (BABYLON) {
  45440. /**
  45441. * The PBR material of BJS following the metal roughness convention.
  45442. *
  45443. * This fits to the PBR convention in the GLTF definition:
  45444. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45445. */
  45446. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45447. __extends(PBRMetallicRoughnessMaterial, _super);
  45448. /**
  45449. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45450. *
  45451. * @param name The material name
  45452. * @param scene The scene the material will be use in.
  45453. */
  45454. function PBRMetallicRoughnessMaterial(name, scene) {
  45455. var _this = _super.call(this, name, scene) || this;
  45456. _this._useRoughnessFromMetallicTextureAlpha = false;
  45457. _this._useRoughnessFromMetallicTextureGreen = true;
  45458. _this._useMetallnessFromMetallicTextureBlue = true;
  45459. _this.metallic = 1.0;
  45460. _this.roughness = 1.0;
  45461. return _this;
  45462. }
  45463. /**
  45464. * Return the currrent class name of the material.
  45465. */
  45466. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45467. return "PBRMetallicRoughnessMaterial";
  45468. };
  45469. /**
  45470. * Return the active textures of the material.
  45471. */
  45472. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45473. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45474. if (this.baseTexture) {
  45475. activeTextures.push(this.baseTexture);
  45476. }
  45477. if (this.metallicRoughnessTexture) {
  45478. activeTextures.push(this.metallicRoughnessTexture);
  45479. }
  45480. return activeTextures;
  45481. };
  45482. /**
  45483. * Checks to see if a texture is used in the material.
  45484. * @param texture - Base texture to use.
  45485. * @returns - Boolean specifying if a texture is used in the material.
  45486. */
  45487. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45488. if (_super.prototype.hasTexture.call(this, texture)) {
  45489. return true;
  45490. }
  45491. if (this.baseTexture === texture) {
  45492. return true;
  45493. }
  45494. if (this.metallicRoughnessTexture === texture) {
  45495. return true;
  45496. }
  45497. return false;
  45498. };
  45499. /**
  45500. * Makes a duplicate of the current material.
  45501. * @param name - name to use for the new material.
  45502. */
  45503. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45504. var _this = this;
  45505. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45506. clone.id = name;
  45507. clone.name = name;
  45508. return clone;
  45509. };
  45510. /**
  45511. * Serialize the material to a parsable JSON object.
  45512. */
  45513. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45515. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45516. return serializationObject;
  45517. };
  45518. /**
  45519. * Parses a JSON object correponding to the serialize function.
  45520. */
  45521. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45522. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45523. };
  45524. __decorate([
  45525. BABYLON.serializeAsColor3(),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45527. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45528. __decorate([
  45529. BABYLON.serializeAsTexture(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45531. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45532. __decorate([
  45533. BABYLON.serialize(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45535. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45536. __decorate([
  45537. BABYLON.serialize(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45539. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45540. __decorate([
  45541. BABYLON.serializeAsTexture(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45543. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45544. return PBRMetallicRoughnessMaterial;
  45545. }(BABYLON.PBRBaseSimpleMaterial));
  45546. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45547. })(BABYLON || (BABYLON = {}));
  45548. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45549. "use strict";
  45550. var BABYLON;
  45551. (function (BABYLON) {
  45552. /**
  45553. * The PBR material of BJS following the specular glossiness convention.
  45554. *
  45555. * This fits to the PBR convention in the GLTF definition:
  45556. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45557. */
  45558. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45559. __extends(PBRSpecularGlossinessMaterial, _super);
  45560. /**
  45561. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45562. *
  45563. * @param name The material name
  45564. * @param scene The scene the material will be use in.
  45565. */
  45566. function PBRSpecularGlossinessMaterial(name, scene) {
  45567. var _this = _super.call(this, name, scene) || this;
  45568. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45569. return _this;
  45570. }
  45571. /**
  45572. * Return the currrent class name of the material.
  45573. */
  45574. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45575. return "PBRSpecularGlossinessMaterial";
  45576. };
  45577. /**
  45578. * Return the active textures of the material.
  45579. */
  45580. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45581. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45582. if (this.diffuseTexture) {
  45583. activeTextures.push(this.diffuseTexture);
  45584. }
  45585. if (this.specularGlossinessTexture) {
  45586. activeTextures.push(this.specularGlossinessTexture);
  45587. }
  45588. return activeTextures;
  45589. };
  45590. /**
  45591. * Checks to see if a texture is used in the material.
  45592. * @param texture - Base texture to use.
  45593. * @returns - Boolean specifying if a texture is used in the material.
  45594. */
  45595. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45596. if (_super.prototype.hasTexture.call(this, texture)) {
  45597. return true;
  45598. }
  45599. if (this.diffuseTexture === texture) {
  45600. return true;
  45601. }
  45602. if (this.specularGlossinessTexture === texture) {
  45603. return true;
  45604. }
  45605. return false;
  45606. };
  45607. /**
  45608. * Makes a duplicate of the current material.
  45609. * @param name - name to use for the new material.
  45610. */
  45611. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45612. var _this = this;
  45613. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45614. clone.id = name;
  45615. clone.name = name;
  45616. return clone;
  45617. };
  45618. /**
  45619. * Serialize the material to a parsable JSON object.
  45620. */
  45621. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45622. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45623. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45624. return serializationObject;
  45625. };
  45626. /**
  45627. * Parses a JSON object correponding to the serialize function.
  45628. */
  45629. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45630. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45631. };
  45632. __decorate([
  45633. BABYLON.serializeAsColor3("diffuse"),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45635. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45636. __decorate([
  45637. BABYLON.serializeAsTexture(),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45639. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45640. __decorate([
  45641. BABYLON.serializeAsColor3("specular"),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45643. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45647. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45648. __decorate([
  45649. BABYLON.serializeAsTexture(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45651. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45652. return PBRSpecularGlossinessMaterial;
  45653. }(BABYLON.PBRBaseSimpleMaterial));
  45654. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45655. })(BABYLON || (BABYLON = {}));
  45656. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45657. "use strict";
  45658. var BABYLON;
  45659. (function (BABYLON) {
  45660. BABYLON.CameraInputTypes = {};
  45661. var CameraInputsManager = /** @class */ (function () {
  45662. function CameraInputsManager(camera) {
  45663. this.attached = {};
  45664. this.camera = camera;
  45665. this.checkInputs = function () { };
  45666. }
  45667. /**
  45668. * Add an input method to a camera.
  45669. * builtin inputs example: camera.inputs.addGamepad();
  45670. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45671. * @param input camera input method
  45672. */
  45673. CameraInputsManager.prototype.add = function (input) {
  45674. var type = input.getSimpleName();
  45675. if (this.attached[type]) {
  45676. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45677. return;
  45678. }
  45679. this.attached[type] = input;
  45680. input.camera = this.camera;
  45681. //for checkInputs, we are dynamically creating a function
  45682. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45683. if (input.checkInputs) {
  45684. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45685. }
  45686. if (this.attachedElement) {
  45687. input.attachControl(this.attachedElement);
  45688. }
  45689. };
  45690. /**
  45691. * Remove a specific input method from a camera
  45692. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45693. * @param inputToRemove camera input method
  45694. */
  45695. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45696. for (var cam in this.attached) {
  45697. var input = this.attached[cam];
  45698. if (input === inputToRemove) {
  45699. input.detachControl(this.attachedElement);
  45700. input.camera = null;
  45701. delete this.attached[cam];
  45702. this.rebuildInputCheck();
  45703. }
  45704. }
  45705. };
  45706. CameraInputsManager.prototype.removeByType = function (inputType) {
  45707. for (var cam in this.attached) {
  45708. var input = this.attached[cam];
  45709. if (input.getClassName() === inputType) {
  45710. input.detachControl(this.attachedElement);
  45711. input.camera = null;
  45712. delete this.attached[cam];
  45713. this.rebuildInputCheck();
  45714. }
  45715. }
  45716. };
  45717. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45718. var current = this.checkInputs;
  45719. return function () {
  45720. current();
  45721. fn();
  45722. };
  45723. };
  45724. CameraInputsManager.prototype.attachInput = function (input) {
  45725. if (this.attachedElement) {
  45726. input.attachControl(this.attachedElement, this.noPreventDefault);
  45727. }
  45728. };
  45729. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45730. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45731. if (this.attachedElement) {
  45732. return;
  45733. }
  45734. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45735. this.attachedElement = element;
  45736. this.noPreventDefault = noPreventDefault;
  45737. for (var cam in this.attached) {
  45738. this.attached[cam].attachControl(element, noPreventDefault);
  45739. }
  45740. };
  45741. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45742. if (disconnect === void 0) { disconnect = false; }
  45743. if (this.attachedElement !== element) {
  45744. return;
  45745. }
  45746. for (var cam in this.attached) {
  45747. this.attached[cam].detachControl(element);
  45748. if (disconnect) {
  45749. this.attached[cam].camera = null;
  45750. }
  45751. }
  45752. this.attachedElement = null;
  45753. };
  45754. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45755. this.checkInputs = function () { };
  45756. for (var cam in this.attached) {
  45757. var input = this.attached[cam];
  45758. if (input.checkInputs) {
  45759. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45760. }
  45761. }
  45762. };
  45763. /**
  45764. * Remove all attached input methods from a camera
  45765. */
  45766. CameraInputsManager.prototype.clear = function () {
  45767. if (this.attachedElement) {
  45768. this.detachElement(this.attachedElement, true);
  45769. }
  45770. this.attached = {};
  45771. this.attachedElement = null;
  45772. this.checkInputs = function () { };
  45773. };
  45774. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45775. var inputs = {};
  45776. for (var cam in this.attached) {
  45777. var input = this.attached[cam];
  45778. var res = BABYLON.SerializationHelper.Serialize(input);
  45779. inputs[input.getClassName()] = res;
  45780. }
  45781. serializedCamera.inputsmgr = inputs;
  45782. };
  45783. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45784. var parsedInputs = parsedCamera.inputsmgr;
  45785. if (parsedInputs) {
  45786. this.clear();
  45787. for (var n in parsedInputs) {
  45788. var construct = BABYLON.CameraInputTypes[n];
  45789. if (construct) {
  45790. var parsedinput = parsedInputs[n];
  45791. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45792. this.add(input);
  45793. }
  45794. }
  45795. }
  45796. else {
  45797. //2016-03-08 this part is for managing backward compatibility
  45798. for (var n in this.attached) {
  45799. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45800. if (construct) {
  45801. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45802. this.remove(this.attached[n]);
  45803. this.add(input);
  45804. }
  45805. }
  45806. }
  45807. };
  45808. return CameraInputsManager;
  45809. }());
  45810. BABYLON.CameraInputsManager = CameraInputsManager;
  45811. })(BABYLON || (BABYLON = {}));
  45812. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45813. "use strict";
  45814. var BABYLON;
  45815. (function (BABYLON) {
  45816. var TargetCamera = /** @class */ (function (_super) {
  45817. __extends(TargetCamera, _super);
  45818. function TargetCamera(name, position, scene) {
  45819. var _this = _super.call(this, name, position, scene) || this;
  45820. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45821. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45822. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45823. _this.speed = 2.0;
  45824. _this.noRotationConstraint = false;
  45825. _this.lockedTarget = null;
  45826. _this._currentTarget = BABYLON.Vector3.Zero();
  45827. _this._viewMatrix = BABYLON.Matrix.Zero();
  45828. _this._camMatrix = BABYLON.Matrix.Zero();
  45829. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45830. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45831. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45832. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45833. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45834. _this._lookAtTemp = BABYLON.Matrix.Zero();
  45835. _this._tempMatrix = BABYLON.Matrix.Zero();
  45836. return _this;
  45837. }
  45838. TargetCamera.prototype.getFrontPosition = function (distance) {
  45839. this.getWorldMatrix();
  45840. var direction = this.getTarget().subtract(this.position);
  45841. direction.normalize();
  45842. direction.scaleInPlace(distance);
  45843. return this.globalPosition.add(direction);
  45844. };
  45845. TargetCamera.prototype._getLockedTargetPosition = function () {
  45846. if (!this.lockedTarget) {
  45847. return null;
  45848. }
  45849. if (this.lockedTarget.absolutePosition) {
  45850. this.lockedTarget.computeWorldMatrix();
  45851. }
  45852. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45853. };
  45854. TargetCamera.prototype.storeState = function () {
  45855. this._storedPosition = this.position.clone();
  45856. this._storedRotation = this.rotation.clone();
  45857. if (this.rotationQuaternion) {
  45858. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45859. }
  45860. return _super.prototype.storeState.call(this);
  45861. };
  45862. /**
  45863. * Restored camera state. You must call storeState() first
  45864. */
  45865. TargetCamera.prototype._restoreStateValues = function () {
  45866. if (!_super.prototype._restoreStateValues.call(this)) {
  45867. return false;
  45868. }
  45869. this.position = this._storedPosition.clone();
  45870. this.rotation = this._storedRotation.clone();
  45871. if (this.rotationQuaternion) {
  45872. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45873. }
  45874. this.cameraDirection.copyFromFloats(0, 0, 0);
  45875. this.cameraRotation.copyFromFloats(0, 0);
  45876. return true;
  45877. };
  45878. // Cache
  45879. TargetCamera.prototype._initCache = function () {
  45880. _super.prototype._initCache.call(this);
  45881. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45882. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45883. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45884. };
  45885. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45886. if (!ignoreParentClass) {
  45887. _super.prototype._updateCache.call(this);
  45888. }
  45889. var lockedTargetPosition = this._getLockedTargetPosition();
  45890. if (!lockedTargetPosition) {
  45891. this._cache.lockedTarget = null;
  45892. }
  45893. else {
  45894. if (!this._cache.lockedTarget) {
  45895. this._cache.lockedTarget = lockedTargetPosition.clone();
  45896. }
  45897. else {
  45898. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45899. }
  45900. }
  45901. this._cache.rotation.copyFrom(this.rotation);
  45902. if (this.rotationQuaternion)
  45903. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45904. };
  45905. // Synchronized
  45906. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45907. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45908. return false;
  45909. }
  45910. var lockedTargetPosition = this._getLockedTargetPosition();
  45911. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45912. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45913. };
  45914. // Methods
  45915. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45916. var engine = this.getEngine();
  45917. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45918. };
  45919. // Target
  45920. TargetCamera.prototype.setTarget = function (target) {
  45921. this.upVector.normalize();
  45922. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45923. this._camMatrix.invert();
  45924. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45925. var vDir = target.subtract(this.position);
  45926. if (vDir.x >= 0.0) {
  45927. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45928. }
  45929. else {
  45930. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45931. }
  45932. this.rotation.z = 0;
  45933. if (isNaN(this.rotation.x)) {
  45934. this.rotation.x = 0;
  45935. }
  45936. if (isNaN(this.rotation.y)) {
  45937. this.rotation.y = 0;
  45938. }
  45939. if (isNaN(this.rotation.z)) {
  45940. this.rotation.z = 0;
  45941. }
  45942. if (this.rotationQuaternion) {
  45943. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45944. }
  45945. };
  45946. /**
  45947. * Return the current target position of the camera. This value is expressed in local space.
  45948. */
  45949. TargetCamera.prototype.getTarget = function () {
  45950. return this._currentTarget;
  45951. };
  45952. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45953. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45954. };
  45955. TargetCamera.prototype._updatePosition = function () {
  45956. if (this.parent) {
  45957. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45958. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45959. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45960. return;
  45961. }
  45962. this.position.addInPlace(this.cameraDirection);
  45963. };
  45964. TargetCamera.prototype._checkInputs = function () {
  45965. var needToMove = this._decideIfNeedsToMove();
  45966. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45967. // Move
  45968. if (needToMove) {
  45969. this._updatePosition();
  45970. }
  45971. // Rotate
  45972. if (needToRotate) {
  45973. this.rotation.x += this.cameraRotation.x;
  45974. this.rotation.y += this.cameraRotation.y;
  45975. //rotate, if quaternion is set and rotation was used
  45976. if (this.rotationQuaternion) {
  45977. var len = this.rotation.lengthSquared();
  45978. if (len) {
  45979. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45980. }
  45981. }
  45982. if (!this.noRotationConstraint) {
  45983. var limit = (Math.PI / 2) * 0.95;
  45984. if (this.rotation.x > limit)
  45985. this.rotation.x = limit;
  45986. if (this.rotation.x < -limit)
  45987. this.rotation.x = -limit;
  45988. }
  45989. }
  45990. // Inertia
  45991. if (needToMove) {
  45992. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45993. this.cameraDirection.x = 0;
  45994. }
  45995. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45996. this.cameraDirection.y = 0;
  45997. }
  45998. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45999. this.cameraDirection.z = 0;
  46000. }
  46001. this.cameraDirection.scaleInPlace(this.inertia);
  46002. }
  46003. if (needToRotate) {
  46004. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46005. this.cameraRotation.x = 0;
  46006. }
  46007. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46008. this.cameraRotation.y = 0;
  46009. }
  46010. this.cameraRotation.scaleInPlace(this.inertia);
  46011. }
  46012. _super.prototype._checkInputs.call(this);
  46013. };
  46014. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46015. if (this.rotationQuaternion) {
  46016. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46017. }
  46018. else {
  46019. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46020. }
  46021. //update the up vector!
  46022. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46023. };
  46024. TargetCamera.prototype._getViewMatrix = function () {
  46025. if (this.lockedTarget) {
  46026. this.setTarget(this._getLockedTargetPosition());
  46027. }
  46028. // Compute
  46029. this._updateCameraRotationMatrix();
  46030. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46031. // Computing target and final matrix
  46032. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46033. if (this.getScene().useRightHandedSystem) {
  46034. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46035. }
  46036. else {
  46037. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46038. }
  46039. return this._viewMatrix;
  46040. };
  46041. /**
  46042. * @override
  46043. * Override Camera.createRigCamera
  46044. */
  46045. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46046. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46047. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46048. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46049. if (!this.rotationQuaternion) {
  46050. this.rotationQuaternion = new BABYLON.Quaternion();
  46051. }
  46052. rigCamera._cameraRigParams = {};
  46053. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46054. }
  46055. return rigCamera;
  46056. }
  46057. return null;
  46058. };
  46059. /**
  46060. * @override
  46061. * Override Camera._updateRigCameras
  46062. */
  46063. TargetCamera.prototype._updateRigCameras = function () {
  46064. var camLeft = this._rigCameras[0];
  46065. var camRight = this._rigCameras[1];
  46066. switch (this.cameraRigMode) {
  46067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46068. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46069. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46070. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46071. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46072. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46073. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46074. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46075. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46076. camLeft.setTarget(this.getTarget());
  46077. camRight.setTarget(this.getTarget());
  46078. break;
  46079. case BABYLON.Camera.RIG_MODE_VR:
  46080. if (camLeft.rotationQuaternion) {
  46081. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46082. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46083. }
  46084. else {
  46085. camLeft.rotation.copyFrom(this.rotation);
  46086. camRight.rotation.copyFrom(this.rotation);
  46087. }
  46088. camLeft.position.copyFrom(this.position);
  46089. camRight.position.copyFrom(this.position);
  46090. break;
  46091. }
  46092. _super.prototype._updateRigCameras.call(this);
  46093. };
  46094. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46095. if (!this._rigCamTransformMatrix) {
  46096. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46097. }
  46098. var target = this.getTarget();
  46099. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46100. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46101. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46102. };
  46103. TargetCamera.prototype.getClassName = function () {
  46104. return "TargetCamera";
  46105. };
  46106. __decorate([
  46107. BABYLON.serializeAsVector3()
  46108. ], TargetCamera.prototype, "rotation", void 0);
  46109. __decorate([
  46110. BABYLON.serialize()
  46111. ], TargetCamera.prototype, "speed", void 0);
  46112. __decorate([
  46113. BABYLON.serializeAsMeshReference("lockedTargetId")
  46114. ], TargetCamera.prototype, "lockedTarget", void 0);
  46115. return TargetCamera;
  46116. }(BABYLON.Camera));
  46117. BABYLON.TargetCamera = TargetCamera;
  46118. })(BABYLON || (BABYLON = {}));
  46119. //# sourceMappingURL=babylon.targetCamera.js.map
  46120. "use strict";
  46121. var BABYLON;
  46122. (function (BABYLON) {
  46123. var FreeCameraMouseInput = /** @class */ (function () {
  46124. function FreeCameraMouseInput(touchEnabled) {
  46125. if (touchEnabled === void 0) { touchEnabled = true; }
  46126. this.touchEnabled = touchEnabled;
  46127. this.buttons = [0, 1, 2];
  46128. this.angularSensibility = 2000.0;
  46129. this.previousPosition = null;
  46130. }
  46131. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46132. var _this = this;
  46133. var engine = this.camera.getEngine();
  46134. if (!this._pointerInput) {
  46135. this._pointerInput = function (p, s) {
  46136. var evt = p.event;
  46137. if (engine.isInVRExclusivePointerMode) {
  46138. return;
  46139. }
  46140. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46141. return;
  46142. }
  46143. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46144. return;
  46145. }
  46146. var srcElement = (evt.srcElement || evt.target);
  46147. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46148. try {
  46149. srcElement.setPointerCapture(evt.pointerId);
  46150. }
  46151. catch (e) {
  46152. //Nothing to do with the error. Execution will continue.
  46153. }
  46154. _this.previousPosition = {
  46155. x: evt.clientX,
  46156. y: evt.clientY
  46157. };
  46158. if (!noPreventDefault) {
  46159. evt.preventDefault();
  46160. element.focus();
  46161. }
  46162. }
  46163. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46164. try {
  46165. srcElement.releasePointerCapture(evt.pointerId);
  46166. }
  46167. catch (e) {
  46168. //Nothing to do with the error.
  46169. }
  46170. _this.previousPosition = null;
  46171. if (!noPreventDefault) {
  46172. evt.preventDefault();
  46173. }
  46174. }
  46175. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46176. if (!_this.previousPosition || engine.isPointerLock) {
  46177. return;
  46178. }
  46179. var offsetX = evt.clientX - _this.previousPosition.x;
  46180. var offsetY = evt.clientY - _this.previousPosition.y;
  46181. if (_this.camera.getScene().useRightHandedSystem) {
  46182. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46183. }
  46184. else {
  46185. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46186. }
  46187. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46188. _this.previousPosition = {
  46189. x: evt.clientX,
  46190. y: evt.clientY
  46191. };
  46192. if (!noPreventDefault) {
  46193. evt.preventDefault();
  46194. }
  46195. }
  46196. };
  46197. }
  46198. this._onMouseMove = function (evt) {
  46199. if (!engine.isPointerLock) {
  46200. return;
  46201. }
  46202. if (engine.isInVRExclusivePointerMode) {
  46203. return;
  46204. }
  46205. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46206. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46207. if (_this.camera.getScene().useRightHandedSystem) {
  46208. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46209. }
  46210. else {
  46211. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46212. }
  46213. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46214. _this.previousPosition = null;
  46215. if (!noPreventDefault) {
  46216. evt.preventDefault();
  46217. }
  46218. };
  46219. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46220. element.addEventListener("mousemove", this._onMouseMove, false);
  46221. };
  46222. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46223. if (this._observer && element) {
  46224. this.camera.getScene().onPointerObservable.remove(this._observer);
  46225. if (this._onMouseMove) {
  46226. element.removeEventListener("mousemove", this._onMouseMove);
  46227. }
  46228. this._observer = null;
  46229. this._onMouseMove = null;
  46230. this.previousPosition = null;
  46231. }
  46232. };
  46233. FreeCameraMouseInput.prototype.getClassName = function () {
  46234. return "FreeCameraMouseInput";
  46235. };
  46236. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46237. return "mouse";
  46238. };
  46239. __decorate([
  46240. BABYLON.serialize()
  46241. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46242. __decorate([
  46243. BABYLON.serialize()
  46244. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46245. return FreeCameraMouseInput;
  46246. }());
  46247. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46248. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46249. })(BABYLON || (BABYLON = {}));
  46250. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46251. "use strict";
  46252. var BABYLON;
  46253. (function (BABYLON) {
  46254. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46255. function FreeCameraKeyboardMoveInput() {
  46256. this._keys = new Array();
  46257. this.keysUp = [38];
  46258. this.keysDown = [40];
  46259. this.keysLeft = [37];
  46260. this.keysRight = [39];
  46261. }
  46262. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46263. var _this = this;
  46264. if (this._onCanvasBlurObserver) {
  46265. return;
  46266. }
  46267. this._scene = this.camera.getScene();
  46268. this._engine = this._scene.getEngine();
  46269. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46270. _this._keys = [];
  46271. });
  46272. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46273. var evt = info.event;
  46274. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46275. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46276. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46277. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46278. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46279. var index = _this._keys.indexOf(evt.keyCode);
  46280. if (index === -1) {
  46281. _this._keys.push(evt.keyCode);
  46282. }
  46283. if (!noPreventDefault) {
  46284. evt.preventDefault();
  46285. }
  46286. }
  46287. }
  46288. else {
  46289. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46290. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46291. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46292. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46293. var index = _this._keys.indexOf(evt.keyCode);
  46294. if (index >= 0) {
  46295. _this._keys.splice(index, 1);
  46296. }
  46297. if (!noPreventDefault) {
  46298. evt.preventDefault();
  46299. }
  46300. }
  46301. }
  46302. });
  46303. };
  46304. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46305. if (this._scene) {
  46306. if (this._onKeyboardObserver) {
  46307. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46308. }
  46309. if (this._onCanvasBlurObserver) {
  46310. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46311. }
  46312. this._onKeyboardObserver = null;
  46313. this._onCanvasBlurObserver = null;
  46314. }
  46315. this._keys = [];
  46316. };
  46317. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46318. if (this._onKeyboardObserver) {
  46319. var camera = this.camera;
  46320. // Keyboard
  46321. for (var index = 0; index < this._keys.length; index++) {
  46322. var keyCode = this._keys[index];
  46323. var speed = camera._computeLocalCameraSpeed();
  46324. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46325. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46326. }
  46327. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46328. camera._localDirection.copyFromFloats(0, 0, speed);
  46329. }
  46330. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46331. camera._localDirection.copyFromFloats(speed, 0, 0);
  46332. }
  46333. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46334. camera._localDirection.copyFromFloats(0, 0, -speed);
  46335. }
  46336. if (camera.getScene().useRightHandedSystem) {
  46337. camera._localDirection.z *= -1;
  46338. }
  46339. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46340. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46341. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46342. }
  46343. }
  46344. };
  46345. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46346. return "FreeCameraKeyboardMoveInput";
  46347. };
  46348. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46349. this._keys = [];
  46350. };
  46351. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46352. return "keyboard";
  46353. };
  46354. __decorate([
  46355. BABYLON.serialize()
  46356. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46357. __decorate([
  46358. BABYLON.serialize()
  46359. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46360. __decorate([
  46361. BABYLON.serialize()
  46362. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46363. __decorate([
  46364. BABYLON.serialize()
  46365. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46366. return FreeCameraKeyboardMoveInput;
  46367. }());
  46368. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46369. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46370. })(BABYLON || (BABYLON = {}));
  46371. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46372. "use strict";
  46373. var BABYLON;
  46374. (function (BABYLON) {
  46375. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46376. __extends(FreeCameraInputsManager, _super);
  46377. function FreeCameraInputsManager(camera) {
  46378. return _super.call(this, camera) || this;
  46379. }
  46380. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46381. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46382. return this;
  46383. };
  46384. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46385. if (touchEnabled === void 0) { touchEnabled = true; }
  46386. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46387. return this;
  46388. };
  46389. FreeCameraInputsManager.prototype.addGamepad = function () {
  46390. this.add(new BABYLON.FreeCameraGamepadInput());
  46391. return this;
  46392. };
  46393. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46394. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46395. return this;
  46396. };
  46397. FreeCameraInputsManager.prototype.addTouch = function () {
  46398. this.add(new BABYLON.FreeCameraTouchInput());
  46399. return this;
  46400. };
  46401. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46402. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46403. return this;
  46404. };
  46405. return FreeCameraInputsManager;
  46406. }(BABYLON.CameraInputsManager));
  46407. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46408. })(BABYLON || (BABYLON = {}));
  46409. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46410. "use strict";
  46411. var BABYLON;
  46412. (function (BABYLON) {
  46413. var FreeCamera = /** @class */ (function (_super) {
  46414. __extends(FreeCamera, _super);
  46415. function FreeCamera(name, position, scene) {
  46416. var _this = _super.call(this, name, position, scene) || this;
  46417. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46418. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46419. _this.checkCollisions = false;
  46420. _this.applyGravity = false;
  46421. _this._needMoveForGravity = false;
  46422. _this._oldPosition = BABYLON.Vector3.Zero();
  46423. _this._diffPosition = BABYLON.Vector3.Zero();
  46424. _this._newPosition = BABYLON.Vector3.Zero();
  46425. // Collisions
  46426. _this._collisionMask = -1;
  46427. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46428. if (collidedMesh === void 0) { collidedMesh = null; }
  46429. //TODO move this to the collision coordinator!
  46430. if (_this.getScene().workerCollisions)
  46431. newPosition.multiplyInPlace(_this._collider._radius);
  46432. var updatePosition = function (newPos) {
  46433. _this._newPosition.copyFrom(newPos);
  46434. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46435. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46436. _this.position.addInPlace(_this._diffPosition);
  46437. if (_this.onCollide && collidedMesh) {
  46438. _this.onCollide(collidedMesh);
  46439. }
  46440. }
  46441. };
  46442. updatePosition(newPosition);
  46443. };
  46444. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46445. _this.inputs.addKeyboard().addMouse();
  46446. return _this;
  46447. }
  46448. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46449. //-- begin properties for backward compatibility for inputs
  46450. /**
  46451. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46452. * Higher values reduce sensitivity.
  46453. */
  46454. get: function () {
  46455. var mouse = this.inputs.attached["mouse"];
  46456. if (mouse)
  46457. return mouse.angularSensibility;
  46458. return 0;
  46459. },
  46460. /**
  46461. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46462. * Higher values reduce sensitivity.
  46463. */
  46464. set: function (value) {
  46465. var mouse = this.inputs.attached["mouse"];
  46466. if (mouse)
  46467. mouse.angularSensibility = value;
  46468. },
  46469. enumerable: true,
  46470. configurable: true
  46471. });
  46472. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46473. get: function () {
  46474. var keyboard = this.inputs.attached["keyboard"];
  46475. if (keyboard)
  46476. return keyboard.keysUp;
  46477. return [];
  46478. },
  46479. set: function (value) {
  46480. var keyboard = this.inputs.attached["keyboard"];
  46481. if (keyboard)
  46482. keyboard.keysUp = value;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46488. get: function () {
  46489. var keyboard = this.inputs.attached["keyboard"];
  46490. if (keyboard)
  46491. return keyboard.keysDown;
  46492. return [];
  46493. },
  46494. set: function (value) {
  46495. var keyboard = this.inputs.attached["keyboard"];
  46496. if (keyboard)
  46497. keyboard.keysDown = value;
  46498. },
  46499. enumerable: true,
  46500. configurable: true
  46501. });
  46502. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46503. get: function () {
  46504. var keyboard = this.inputs.attached["keyboard"];
  46505. if (keyboard)
  46506. return keyboard.keysLeft;
  46507. return [];
  46508. },
  46509. set: function (value) {
  46510. var keyboard = this.inputs.attached["keyboard"];
  46511. if (keyboard)
  46512. keyboard.keysLeft = value;
  46513. },
  46514. enumerable: true,
  46515. configurable: true
  46516. });
  46517. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46518. get: function () {
  46519. var keyboard = this.inputs.attached["keyboard"];
  46520. if (keyboard)
  46521. return keyboard.keysRight;
  46522. return [];
  46523. },
  46524. set: function (value) {
  46525. var keyboard = this.inputs.attached["keyboard"];
  46526. if (keyboard)
  46527. keyboard.keysRight = value;
  46528. },
  46529. enumerable: true,
  46530. configurable: true
  46531. });
  46532. // Controls
  46533. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46534. this.inputs.attachElement(element, noPreventDefault);
  46535. };
  46536. FreeCamera.prototype.detachControl = function (element) {
  46537. this.inputs.detachElement(element);
  46538. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46539. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46540. };
  46541. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46542. get: function () {
  46543. return this._collisionMask;
  46544. },
  46545. set: function (mask) {
  46546. this._collisionMask = !isNaN(mask) ? mask : -1;
  46547. },
  46548. enumerable: true,
  46549. configurable: true
  46550. });
  46551. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46552. var globalPosition;
  46553. if (this.parent) {
  46554. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46555. }
  46556. else {
  46557. globalPosition = this.position;
  46558. }
  46559. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46560. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46561. if (!this._collider) {
  46562. this._collider = new BABYLON.Collider();
  46563. }
  46564. this._collider._radius = this.ellipsoid;
  46565. this._collider.collisionMask = this._collisionMask;
  46566. //no need for clone, as long as gravity is not on.
  46567. var actualDisplacement = displacement;
  46568. //add gravity to the direction to prevent the dual-collision checking
  46569. if (this.applyGravity) {
  46570. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46571. actualDisplacement = displacement.add(this.getScene().gravity);
  46572. }
  46573. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46574. };
  46575. FreeCamera.prototype._checkInputs = function () {
  46576. if (!this._localDirection) {
  46577. this._localDirection = BABYLON.Vector3.Zero();
  46578. this._transformedDirection = BABYLON.Vector3.Zero();
  46579. }
  46580. this.inputs.checkInputs();
  46581. _super.prototype._checkInputs.call(this);
  46582. };
  46583. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46584. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46585. };
  46586. FreeCamera.prototype._updatePosition = function () {
  46587. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46588. this._collideWithWorld(this.cameraDirection);
  46589. }
  46590. else {
  46591. _super.prototype._updatePosition.call(this);
  46592. }
  46593. };
  46594. FreeCamera.prototype.dispose = function () {
  46595. this.inputs.clear();
  46596. _super.prototype.dispose.call(this);
  46597. };
  46598. FreeCamera.prototype.getClassName = function () {
  46599. return "FreeCamera";
  46600. };
  46601. __decorate([
  46602. BABYLON.serializeAsVector3()
  46603. ], FreeCamera.prototype, "ellipsoid", void 0);
  46604. __decorate([
  46605. BABYLON.serializeAsVector3()
  46606. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46607. __decorate([
  46608. BABYLON.serialize()
  46609. ], FreeCamera.prototype, "checkCollisions", void 0);
  46610. __decorate([
  46611. BABYLON.serialize()
  46612. ], FreeCamera.prototype, "applyGravity", void 0);
  46613. return FreeCamera;
  46614. }(BABYLON.TargetCamera));
  46615. BABYLON.FreeCamera = FreeCamera;
  46616. })(BABYLON || (BABYLON = {}));
  46617. //# sourceMappingURL=babylon.freeCamera.js.map
  46618. "use strict";
  46619. var BABYLON;
  46620. (function (BABYLON) {
  46621. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46622. function ArcRotateCameraKeyboardMoveInput() {
  46623. this._keys = new Array();
  46624. this.keysUp = [38];
  46625. this.keysDown = [40];
  46626. this.keysLeft = [37];
  46627. this.keysRight = [39];
  46628. this.keysReset = [220];
  46629. this.panningSensibility = 50.0;
  46630. this.zoomingSensibility = 25.0;
  46631. this.useAltToZoom = true;
  46632. }
  46633. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46634. var _this = this;
  46635. if (this._onCanvasBlurObserver) {
  46636. return;
  46637. }
  46638. this._scene = this.camera.getScene();
  46639. this._engine = this._scene.getEngine();
  46640. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46641. _this._keys = [];
  46642. });
  46643. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46644. var evt = info.event;
  46645. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46646. _this._ctrlPressed = evt.ctrlKey;
  46647. _this._altPressed = evt.altKey;
  46648. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46649. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46650. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46651. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46652. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46653. var index = _this._keys.indexOf(evt.keyCode);
  46654. if (index === -1) {
  46655. _this._keys.push(evt.keyCode);
  46656. }
  46657. if (evt.preventDefault) {
  46658. if (!noPreventDefault) {
  46659. evt.preventDefault();
  46660. }
  46661. }
  46662. }
  46663. }
  46664. else {
  46665. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46666. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46667. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46668. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46669. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46670. var index = _this._keys.indexOf(evt.keyCode);
  46671. if (index >= 0) {
  46672. _this._keys.splice(index, 1);
  46673. }
  46674. if (evt.preventDefault) {
  46675. if (!noPreventDefault) {
  46676. evt.preventDefault();
  46677. }
  46678. }
  46679. }
  46680. }
  46681. });
  46682. };
  46683. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46684. if (this._scene) {
  46685. if (this._onKeyboardObserver) {
  46686. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46687. }
  46688. if (this._onCanvasBlurObserver) {
  46689. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46690. }
  46691. this._onKeyboardObserver = null;
  46692. this._onCanvasBlurObserver = null;
  46693. }
  46694. this._keys = [];
  46695. };
  46696. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46697. if (this._onKeyboardObserver) {
  46698. var camera = this.camera;
  46699. for (var index = 0; index < this._keys.length; index++) {
  46700. var keyCode = this._keys[index];
  46701. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46702. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46703. camera.inertialPanningX -= 1 / this.panningSensibility;
  46704. }
  46705. else {
  46706. camera.inertialAlphaOffset -= 0.01;
  46707. }
  46708. }
  46709. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46710. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46711. camera.inertialPanningY += 1 / this.panningSensibility;
  46712. }
  46713. else if (this._altPressed && this.useAltToZoom) {
  46714. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46715. }
  46716. else {
  46717. camera.inertialBetaOffset -= 0.01;
  46718. }
  46719. }
  46720. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46721. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46722. camera.inertialPanningX += 1 / this.panningSensibility;
  46723. }
  46724. else {
  46725. camera.inertialAlphaOffset += 0.01;
  46726. }
  46727. }
  46728. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46729. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46730. camera.inertialPanningY -= 1 / this.panningSensibility;
  46731. }
  46732. else if (this._altPressed && this.useAltToZoom) {
  46733. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46734. }
  46735. else {
  46736. camera.inertialBetaOffset += 0.01;
  46737. }
  46738. }
  46739. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46740. camera.restoreState();
  46741. }
  46742. }
  46743. }
  46744. };
  46745. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46746. return "ArcRotateCameraKeyboardMoveInput";
  46747. };
  46748. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46749. return "keyboard";
  46750. };
  46751. __decorate([
  46752. BABYLON.serialize()
  46753. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46754. __decorate([
  46755. BABYLON.serialize()
  46756. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46757. __decorate([
  46758. BABYLON.serialize()
  46759. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46760. __decorate([
  46761. BABYLON.serialize()
  46762. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46763. __decorate([
  46764. BABYLON.serialize()
  46765. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46766. __decorate([
  46767. BABYLON.serialize()
  46768. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46769. __decorate([
  46770. BABYLON.serialize()
  46771. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46772. __decorate([
  46773. BABYLON.serialize()
  46774. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46775. return ArcRotateCameraKeyboardMoveInput;
  46776. }());
  46777. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46778. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46779. })(BABYLON || (BABYLON = {}));
  46780. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46781. "use strict";
  46782. var BABYLON;
  46783. (function (BABYLON) {
  46784. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46785. function ArcRotateCameraMouseWheelInput() {
  46786. this.wheelPrecision = 3.0;
  46787. /**
  46788. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46789. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46790. */
  46791. this.wheelDeltaPercentage = 0;
  46792. }
  46793. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46794. var _this = this;
  46795. this._wheel = function (p, s) {
  46796. //sanity check - this should be a PointerWheel event.
  46797. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46798. return;
  46799. var event = p.event;
  46800. var delta = 0;
  46801. if (event.wheelDelta) {
  46802. if (_this.wheelDeltaPercentage) {
  46803. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46804. if (event.wheelDelta > 0) {
  46805. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46806. }
  46807. else {
  46808. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46809. }
  46810. }
  46811. else {
  46812. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46813. }
  46814. }
  46815. else if (event.detail) {
  46816. delta = -event.detail / _this.wheelPrecision;
  46817. }
  46818. if (delta)
  46819. _this.camera.inertialRadiusOffset += delta;
  46820. if (event.preventDefault) {
  46821. if (!noPreventDefault) {
  46822. event.preventDefault();
  46823. }
  46824. }
  46825. };
  46826. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46827. };
  46828. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46829. if (this._observer && element) {
  46830. this.camera.getScene().onPointerObservable.remove(this._observer);
  46831. this._observer = null;
  46832. this._wheel = null;
  46833. }
  46834. };
  46835. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46836. return "ArcRotateCameraMouseWheelInput";
  46837. };
  46838. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46839. return "mousewheel";
  46840. };
  46841. __decorate([
  46842. BABYLON.serialize()
  46843. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46844. __decorate([
  46845. BABYLON.serialize()
  46846. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46847. return ArcRotateCameraMouseWheelInput;
  46848. }());
  46849. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46850. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46851. })(BABYLON || (BABYLON = {}));
  46852. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46853. "use strict";
  46854. var BABYLON;
  46855. (function (BABYLON) {
  46856. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46857. function ArcRotateCameraPointersInput() {
  46858. this.buttons = [0, 1, 2];
  46859. this.angularSensibilityX = 1000.0;
  46860. this.angularSensibilityY = 1000.0;
  46861. this.pinchPrecision = 12.0;
  46862. /**
  46863. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46864. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46865. */
  46866. this.pinchDeltaPercentage = 0;
  46867. this.panningSensibility = 1000.0;
  46868. this.multiTouchPanning = true;
  46869. this.multiTouchPanAndZoom = true;
  46870. this._isPanClick = false;
  46871. this.pinchInwards = true;
  46872. }
  46873. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46874. var _this = this;
  46875. var engine = this.camera.getEngine();
  46876. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46877. var pointA = null;
  46878. var pointB = null;
  46879. var previousPinchSquaredDistance = 0;
  46880. var initialDistance = 0;
  46881. var twoFingerActivityCount = 0;
  46882. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46883. this._pointerInput = function (p, s) {
  46884. var evt = p.event;
  46885. var isTouch = p.event.pointerType === "touch";
  46886. if (engine.isInVRExclusivePointerMode) {
  46887. return;
  46888. }
  46889. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46890. return;
  46891. }
  46892. var srcElement = (evt.srcElement || evt.target);
  46893. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46894. try {
  46895. srcElement.setPointerCapture(evt.pointerId);
  46896. }
  46897. catch (e) {
  46898. //Nothing to do with the error. Execution will continue.
  46899. }
  46900. // Manage panning with pan button click
  46901. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46902. // manage pointers
  46903. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46904. if (pointA === null) {
  46905. pointA = cacheSoloPointer;
  46906. }
  46907. else if (pointB === null) {
  46908. pointB = cacheSoloPointer;
  46909. }
  46910. if (!noPreventDefault) {
  46911. evt.preventDefault();
  46912. element.focus();
  46913. }
  46914. }
  46915. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46916. _this.camera.restoreState();
  46917. }
  46918. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46919. try {
  46920. srcElement.releasePointerCapture(evt.pointerId);
  46921. }
  46922. catch (e) {
  46923. //Nothing to do with the error.
  46924. }
  46925. cacheSoloPointer = null;
  46926. previousPinchSquaredDistance = 0;
  46927. previousMultiTouchPanPosition.isPaning = false;
  46928. previousMultiTouchPanPosition.isPinching = false;
  46929. twoFingerActivityCount = 0;
  46930. initialDistance = 0;
  46931. if (!isTouch) {
  46932. pointB = null; // Mouse and pen are mono pointer
  46933. }
  46934. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46935. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46936. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46937. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46938. if (engine._badOS) {
  46939. pointA = pointB = null;
  46940. }
  46941. else {
  46942. //only remove the impacted pointer in case of multitouch allowing on most
  46943. //platforms switching from rotate to zoom and pan seamlessly.
  46944. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46945. pointA = pointB;
  46946. pointB = null;
  46947. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46948. }
  46949. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46950. pointB = null;
  46951. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46952. }
  46953. else {
  46954. pointA = pointB = null;
  46955. }
  46956. }
  46957. if (!noPreventDefault) {
  46958. evt.preventDefault();
  46959. }
  46960. }
  46961. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46962. if (!noPreventDefault) {
  46963. evt.preventDefault();
  46964. }
  46965. // One button down
  46966. if (pointA && pointB === null && cacheSoloPointer) {
  46967. if (_this.panningSensibility !== 0 &&
  46968. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46969. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46970. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46971. }
  46972. else {
  46973. var offsetX = evt.clientX - cacheSoloPointer.x;
  46974. var offsetY = evt.clientY - cacheSoloPointer.y;
  46975. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46976. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46977. }
  46978. cacheSoloPointer.x = evt.clientX;
  46979. cacheSoloPointer.y = evt.clientY;
  46980. }
  46981. else if (pointA && pointB) {
  46982. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46983. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46984. ed.x = evt.clientX;
  46985. ed.y = evt.clientY;
  46986. var direction = _this.pinchInwards ? 1 : -1;
  46987. var distX = pointA.x - pointB.x;
  46988. var distY = pointA.y - pointB.y;
  46989. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46990. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46991. if (previousPinchSquaredDistance === 0) {
  46992. initialDistance = pinchDistance;
  46993. previousPinchSquaredDistance = pinchSquaredDistance;
  46994. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46995. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46996. return;
  46997. }
  46998. if (_this.multiTouchPanAndZoom) {
  46999. if (_this.pinchDeltaPercentage) {
  47000. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47001. }
  47002. else {
  47003. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47004. (_this.pinchPrecision *
  47005. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47006. direction);
  47007. }
  47008. if (_this.panningSensibility !== 0) {
  47009. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47010. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47011. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47012. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47013. previousMultiTouchPanPosition.x = pointersCenterX;
  47014. previousMultiTouchPanPosition.y = pointersCenterY;
  47015. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47016. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47017. }
  47018. }
  47019. else {
  47020. twoFingerActivityCount++;
  47021. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47022. if (_this.pinchDeltaPercentage) {
  47023. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47024. }
  47025. else {
  47026. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47027. (_this.pinchPrecision *
  47028. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47029. direction);
  47030. }
  47031. previousMultiTouchPanPosition.isPaning = false;
  47032. previousMultiTouchPanPosition.isPinching = true;
  47033. }
  47034. else {
  47035. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47036. if (!previousMultiTouchPanPosition.isPaning) {
  47037. previousMultiTouchPanPosition.isPaning = true;
  47038. previousMultiTouchPanPosition.isPinching = false;
  47039. previousMultiTouchPanPosition.x = ed.x;
  47040. previousMultiTouchPanPosition.y = ed.y;
  47041. return;
  47042. }
  47043. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47044. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47045. }
  47046. }
  47047. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47048. previousMultiTouchPanPosition.x = ed.x;
  47049. previousMultiTouchPanPosition.y = ed.y;
  47050. }
  47051. }
  47052. previousPinchSquaredDistance = pinchSquaredDistance;
  47053. }
  47054. }
  47055. };
  47056. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47057. this._onContextMenu = function (evt) {
  47058. evt.preventDefault();
  47059. };
  47060. if (!this.camera._useCtrlForPanning) {
  47061. element.addEventListener("contextmenu", this._onContextMenu, false);
  47062. }
  47063. this._onLostFocus = function () {
  47064. //this._keys = [];
  47065. pointA = pointB = null;
  47066. previousPinchSquaredDistance = 0;
  47067. previousMultiTouchPanPosition.isPaning = false;
  47068. previousMultiTouchPanPosition.isPinching = false;
  47069. twoFingerActivityCount = 0;
  47070. cacheSoloPointer = null;
  47071. initialDistance = 0;
  47072. };
  47073. this._onMouseMove = function (evt) {
  47074. if (!engine.isPointerLock) {
  47075. return;
  47076. }
  47077. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47078. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47079. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47080. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47081. if (!noPreventDefault) {
  47082. evt.preventDefault();
  47083. }
  47084. };
  47085. this._onGestureStart = function (e) {
  47086. if (window.MSGesture === undefined) {
  47087. return;
  47088. }
  47089. if (!_this._MSGestureHandler) {
  47090. _this._MSGestureHandler = new MSGesture();
  47091. _this._MSGestureHandler.target = element;
  47092. }
  47093. _this._MSGestureHandler.addPointer(e.pointerId);
  47094. };
  47095. this._onGesture = function (e) {
  47096. _this.camera.radius *= e.scale;
  47097. if (e.preventDefault) {
  47098. if (!noPreventDefault) {
  47099. e.stopPropagation();
  47100. e.preventDefault();
  47101. }
  47102. }
  47103. };
  47104. element.addEventListener("mousemove", this._onMouseMove, false);
  47105. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47106. element.addEventListener("MSGestureChange", this._onGesture, false);
  47107. BABYLON.Tools.RegisterTopRootEvents([
  47108. { name: "blur", handler: this._onLostFocus }
  47109. ]);
  47110. };
  47111. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47112. if (this._onLostFocus) {
  47113. BABYLON.Tools.UnregisterTopRootEvents([
  47114. { name: "blur", handler: this._onLostFocus }
  47115. ]);
  47116. }
  47117. if (element && this._observer) {
  47118. this.camera.getScene().onPointerObservable.remove(this._observer);
  47119. this._observer = null;
  47120. if (this._onContextMenu) {
  47121. element.removeEventListener("contextmenu", this._onContextMenu);
  47122. }
  47123. if (this._onMouseMove) {
  47124. element.removeEventListener("mousemove", this._onMouseMove);
  47125. }
  47126. if (this._onGestureStart) {
  47127. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47128. }
  47129. if (this._onGesture) {
  47130. element.removeEventListener("MSGestureChange", this._onGesture);
  47131. }
  47132. this._isPanClick = false;
  47133. this.pinchInwards = true;
  47134. this._onMouseMove = null;
  47135. this._onGestureStart = null;
  47136. this._onGesture = null;
  47137. this._MSGestureHandler = null;
  47138. this._onLostFocus = null;
  47139. this._onContextMenu = null;
  47140. }
  47141. };
  47142. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47143. return "ArcRotateCameraPointersInput";
  47144. };
  47145. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47146. return "pointers";
  47147. };
  47148. __decorate([
  47149. BABYLON.serialize()
  47150. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47151. __decorate([
  47152. BABYLON.serialize()
  47153. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47154. __decorate([
  47155. BABYLON.serialize()
  47156. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47157. __decorate([
  47158. BABYLON.serialize()
  47159. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47160. __decorate([
  47161. BABYLON.serialize()
  47162. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47163. __decorate([
  47164. BABYLON.serialize()
  47165. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47166. __decorate([
  47167. BABYLON.serialize()
  47168. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47169. __decorate([
  47170. BABYLON.serialize()
  47171. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47172. return ArcRotateCameraPointersInput;
  47173. }());
  47174. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47175. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47176. })(BABYLON || (BABYLON = {}));
  47177. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47178. "use strict";
  47179. var BABYLON;
  47180. (function (BABYLON) {
  47181. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47182. __extends(ArcRotateCameraInputsManager, _super);
  47183. function ArcRotateCameraInputsManager(camera) {
  47184. return _super.call(this, camera) || this;
  47185. }
  47186. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47187. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47188. return this;
  47189. };
  47190. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47191. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47192. return this;
  47193. };
  47194. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47195. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47196. return this;
  47197. };
  47198. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47199. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47200. return this;
  47201. };
  47202. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47203. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47204. return this;
  47205. };
  47206. return ArcRotateCameraInputsManager;
  47207. }(BABYLON.CameraInputsManager));
  47208. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47209. })(BABYLON || (BABYLON = {}));
  47210. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47211. "use strict";
  47212. var BABYLON;
  47213. (function (BABYLON) {
  47214. var ArcRotateCamera = /** @class */ (function (_super) {
  47215. __extends(ArcRotateCamera, _super);
  47216. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47217. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47218. _this.inertialAlphaOffset = 0;
  47219. _this.inertialBetaOffset = 0;
  47220. _this.inertialRadiusOffset = 0;
  47221. _this.lowerAlphaLimit = null;
  47222. _this.upperAlphaLimit = null;
  47223. _this.lowerBetaLimit = 0.01;
  47224. _this.upperBetaLimit = Math.PI;
  47225. _this.lowerRadiusLimit = null;
  47226. _this.upperRadiusLimit = null;
  47227. _this.inertialPanningX = 0;
  47228. _this.inertialPanningY = 0;
  47229. _this.pinchToPanMaxDistance = 20;
  47230. _this.panningDistanceLimit = null;
  47231. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47232. _this.panningInertia = 0.9;
  47233. //-- end properties for backward compatibility for inputs
  47234. _this.zoomOnFactor = 1;
  47235. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47236. _this.allowUpsideDown = true;
  47237. _this._viewMatrix = new BABYLON.Matrix();
  47238. // Panning
  47239. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47240. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47241. _this.checkCollisions = false;
  47242. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47243. _this._previousPosition = BABYLON.Vector3.Zero();
  47244. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47245. _this._newPosition = BABYLON.Vector3.Zero();
  47246. _this._computationVector = BABYLON.Vector3.Zero();
  47247. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47248. if (collidedMesh === void 0) { collidedMesh = null; }
  47249. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47250. newPosition.multiplyInPlace(_this._collider._radius);
  47251. }
  47252. if (!collidedMesh) {
  47253. _this._previousPosition.copyFrom(_this.position);
  47254. }
  47255. else {
  47256. _this.setPosition(newPosition);
  47257. if (_this.onCollide) {
  47258. _this.onCollide(collidedMesh);
  47259. }
  47260. }
  47261. // Recompute because of constraints
  47262. var cosa = Math.cos(_this.alpha);
  47263. var sina = Math.sin(_this.alpha);
  47264. var cosb = Math.cos(_this.beta);
  47265. var sinb = Math.sin(_this.beta);
  47266. if (sinb === 0) {
  47267. sinb = 0.0001;
  47268. }
  47269. var target = _this._getTargetPosition();
  47270. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47271. target.addToRef(_this._computationVector, _this._newPosition);
  47272. _this.position.copyFrom(_this._newPosition);
  47273. var up = _this.upVector;
  47274. if (_this.allowUpsideDown && _this.beta < 0) {
  47275. up = up.clone();
  47276. up = up.negate();
  47277. }
  47278. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47279. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47280. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47281. _this._collisionTriggered = false;
  47282. };
  47283. _this._target = BABYLON.Vector3.Zero();
  47284. if (target) {
  47285. _this.setTarget(target);
  47286. }
  47287. _this.alpha = alpha;
  47288. _this.beta = beta;
  47289. _this.radius = radius;
  47290. _this.getViewMatrix();
  47291. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47292. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47293. return _this;
  47294. }
  47295. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47296. get: function () {
  47297. return this._target;
  47298. },
  47299. set: function (value) {
  47300. this.setTarget(value);
  47301. },
  47302. enumerable: true,
  47303. configurable: true
  47304. });
  47305. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47306. //-- begin properties for backward compatibility for inputs
  47307. get: function () {
  47308. var pointers = this.inputs.attached["pointers"];
  47309. if (pointers)
  47310. return pointers.angularSensibilityX;
  47311. return 0;
  47312. },
  47313. set: function (value) {
  47314. var pointers = this.inputs.attached["pointers"];
  47315. if (pointers) {
  47316. pointers.angularSensibilityX = value;
  47317. }
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47323. get: function () {
  47324. var pointers = this.inputs.attached["pointers"];
  47325. if (pointers)
  47326. return pointers.angularSensibilityY;
  47327. return 0;
  47328. },
  47329. set: function (value) {
  47330. var pointers = this.inputs.attached["pointers"];
  47331. if (pointers) {
  47332. pointers.angularSensibilityY = value;
  47333. }
  47334. },
  47335. enumerable: true,
  47336. configurable: true
  47337. });
  47338. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47339. get: function () {
  47340. var pointers = this.inputs.attached["pointers"];
  47341. if (pointers)
  47342. return pointers.pinchPrecision;
  47343. return 0;
  47344. },
  47345. set: function (value) {
  47346. var pointers = this.inputs.attached["pointers"];
  47347. if (pointers) {
  47348. pointers.pinchPrecision = value;
  47349. }
  47350. },
  47351. enumerable: true,
  47352. configurable: true
  47353. });
  47354. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47355. get: function () {
  47356. var pointers = this.inputs.attached["pointers"];
  47357. if (pointers)
  47358. return pointers.pinchDeltaPercentage;
  47359. return 0;
  47360. },
  47361. set: function (value) {
  47362. var pointers = this.inputs.attached["pointers"];
  47363. if (pointers) {
  47364. pointers.pinchDeltaPercentage = value;
  47365. }
  47366. },
  47367. enumerable: true,
  47368. configurable: true
  47369. });
  47370. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47371. get: function () {
  47372. var pointers = this.inputs.attached["pointers"];
  47373. if (pointers)
  47374. return pointers.panningSensibility;
  47375. return 0;
  47376. },
  47377. set: function (value) {
  47378. var pointers = this.inputs.attached["pointers"];
  47379. if (pointers) {
  47380. pointers.panningSensibility = value;
  47381. }
  47382. },
  47383. enumerable: true,
  47384. configurable: true
  47385. });
  47386. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47387. get: function () {
  47388. var keyboard = this.inputs.attached["keyboard"];
  47389. if (keyboard)
  47390. return keyboard.keysUp;
  47391. return [];
  47392. },
  47393. set: function (value) {
  47394. var keyboard = this.inputs.attached["keyboard"];
  47395. if (keyboard)
  47396. keyboard.keysUp = value;
  47397. },
  47398. enumerable: true,
  47399. configurable: true
  47400. });
  47401. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47402. get: function () {
  47403. var keyboard = this.inputs.attached["keyboard"];
  47404. if (keyboard)
  47405. return keyboard.keysDown;
  47406. return [];
  47407. },
  47408. set: function (value) {
  47409. var keyboard = this.inputs.attached["keyboard"];
  47410. if (keyboard)
  47411. keyboard.keysDown = value;
  47412. },
  47413. enumerable: true,
  47414. configurable: true
  47415. });
  47416. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47417. get: function () {
  47418. var keyboard = this.inputs.attached["keyboard"];
  47419. if (keyboard)
  47420. return keyboard.keysLeft;
  47421. return [];
  47422. },
  47423. set: function (value) {
  47424. var keyboard = this.inputs.attached["keyboard"];
  47425. if (keyboard)
  47426. keyboard.keysLeft = value;
  47427. },
  47428. enumerable: true,
  47429. configurable: true
  47430. });
  47431. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47432. get: function () {
  47433. var keyboard = this.inputs.attached["keyboard"];
  47434. if (keyboard)
  47435. return keyboard.keysRight;
  47436. return [];
  47437. },
  47438. set: function (value) {
  47439. var keyboard = this.inputs.attached["keyboard"];
  47440. if (keyboard)
  47441. keyboard.keysRight = value;
  47442. },
  47443. enumerable: true,
  47444. configurable: true
  47445. });
  47446. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47447. get: function () {
  47448. var mousewheel = this.inputs.attached["mousewheel"];
  47449. if (mousewheel)
  47450. return mousewheel.wheelPrecision;
  47451. return 0;
  47452. },
  47453. set: function (value) {
  47454. var mousewheel = this.inputs.attached["mousewheel"];
  47455. if (mousewheel)
  47456. mousewheel.wheelPrecision = value;
  47457. },
  47458. enumerable: true,
  47459. configurable: true
  47460. });
  47461. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47462. get: function () {
  47463. var mousewheel = this.inputs.attached["mousewheel"];
  47464. if (mousewheel)
  47465. return mousewheel.wheelDeltaPercentage;
  47466. return 0;
  47467. },
  47468. set: function (value) {
  47469. var mousewheel = this.inputs.attached["mousewheel"];
  47470. if (mousewheel)
  47471. mousewheel.wheelDeltaPercentage = value;
  47472. },
  47473. enumerable: true,
  47474. configurable: true
  47475. });
  47476. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47477. get: function () {
  47478. return this._bouncingBehavior;
  47479. },
  47480. enumerable: true,
  47481. configurable: true
  47482. });
  47483. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47484. get: function () {
  47485. return this._bouncingBehavior != null;
  47486. },
  47487. set: function (value) {
  47488. if (value === this.useBouncingBehavior) {
  47489. return;
  47490. }
  47491. if (value) {
  47492. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47493. this.addBehavior(this._bouncingBehavior);
  47494. }
  47495. else if (this._bouncingBehavior) {
  47496. this.removeBehavior(this._bouncingBehavior);
  47497. this._bouncingBehavior = null;
  47498. }
  47499. },
  47500. enumerable: true,
  47501. configurable: true
  47502. });
  47503. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47504. get: function () {
  47505. return this._framingBehavior;
  47506. },
  47507. enumerable: true,
  47508. configurable: true
  47509. });
  47510. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47511. get: function () {
  47512. return this._framingBehavior != null;
  47513. },
  47514. set: function (value) {
  47515. if (value === this.useFramingBehavior) {
  47516. return;
  47517. }
  47518. if (value) {
  47519. this._framingBehavior = new BABYLON.FramingBehavior();
  47520. this.addBehavior(this._framingBehavior);
  47521. }
  47522. else if (this._framingBehavior) {
  47523. this.removeBehavior(this._framingBehavior);
  47524. this._framingBehavior = null;
  47525. }
  47526. },
  47527. enumerable: true,
  47528. configurable: true
  47529. });
  47530. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47531. get: function () {
  47532. return this._autoRotationBehavior;
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47538. get: function () {
  47539. return this._autoRotationBehavior != null;
  47540. },
  47541. set: function (value) {
  47542. if (value === this.useAutoRotationBehavior) {
  47543. return;
  47544. }
  47545. if (value) {
  47546. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47547. this.addBehavior(this._autoRotationBehavior);
  47548. }
  47549. else if (this._autoRotationBehavior) {
  47550. this.removeBehavior(this._autoRotationBehavior);
  47551. this._autoRotationBehavior = null;
  47552. }
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. // Cache
  47558. ArcRotateCamera.prototype._initCache = function () {
  47559. _super.prototype._initCache.call(this);
  47560. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47561. this._cache.alpha = undefined;
  47562. this._cache.beta = undefined;
  47563. this._cache.radius = undefined;
  47564. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47565. };
  47566. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47567. if (!ignoreParentClass) {
  47568. _super.prototype._updateCache.call(this);
  47569. }
  47570. this._cache._target.copyFrom(this._getTargetPosition());
  47571. this._cache.alpha = this.alpha;
  47572. this._cache.beta = this.beta;
  47573. this._cache.radius = this.radius;
  47574. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47575. };
  47576. ArcRotateCamera.prototype._getTargetPosition = function () {
  47577. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47578. var pos = this._targetHost.getAbsolutePosition();
  47579. if (this._targetBoundingCenter) {
  47580. pos.addToRef(this._targetBoundingCenter, this._target);
  47581. }
  47582. else {
  47583. this._target.copyFrom(pos);
  47584. }
  47585. }
  47586. var lockedTargetPosition = this._getLockedTargetPosition();
  47587. if (lockedTargetPosition) {
  47588. return lockedTargetPosition;
  47589. }
  47590. return this._target;
  47591. };
  47592. ArcRotateCamera.prototype.storeState = function () {
  47593. this._storedAlpha = this.alpha;
  47594. this._storedBeta = this.beta;
  47595. this._storedRadius = this.radius;
  47596. this._storedTarget = this._getTargetPosition().clone();
  47597. return _super.prototype.storeState.call(this);
  47598. };
  47599. /**
  47600. * Restored camera state. You must call storeState() first
  47601. */
  47602. ArcRotateCamera.prototype._restoreStateValues = function () {
  47603. if (!_super.prototype._restoreStateValues.call(this)) {
  47604. return false;
  47605. }
  47606. this.alpha = this._storedAlpha;
  47607. this.beta = this._storedBeta;
  47608. this.radius = this._storedRadius;
  47609. this.setTarget(this._storedTarget.clone());
  47610. this.inertialAlphaOffset = 0;
  47611. this.inertialBetaOffset = 0;
  47612. this.inertialRadiusOffset = 0;
  47613. this.inertialPanningX = 0;
  47614. this.inertialPanningY = 0;
  47615. return true;
  47616. };
  47617. // Synchronized
  47618. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47619. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47620. return false;
  47621. return this._cache._target.equals(this._getTargetPosition())
  47622. && this._cache.alpha === this.alpha
  47623. && this._cache.beta === this.beta
  47624. && this._cache.radius === this.radius
  47625. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47626. };
  47627. // Methods
  47628. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47629. var _this = this;
  47630. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47631. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47632. this._useCtrlForPanning = useCtrlForPanning;
  47633. this._panningMouseButton = panningMouseButton;
  47634. this.inputs.attachElement(element, noPreventDefault);
  47635. this._reset = function () {
  47636. _this.inertialAlphaOffset = 0;
  47637. _this.inertialBetaOffset = 0;
  47638. _this.inertialRadiusOffset = 0;
  47639. _this.inertialPanningX = 0;
  47640. _this.inertialPanningY = 0;
  47641. };
  47642. };
  47643. ArcRotateCamera.prototype.detachControl = function (element) {
  47644. this.inputs.detachElement(element);
  47645. if (this._reset) {
  47646. this._reset();
  47647. }
  47648. };
  47649. ArcRotateCamera.prototype._checkInputs = function () {
  47650. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47651. if (this._collisionTriggered) {
  47652. return;
  47653. }
  47654. this.inputs.checkInputs();
  47655. // Inertia
  47656. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47657. if (this.getScene().useRightHandedSystem) {
  47658. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47659. }
  47660. else {
  47661. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47662. }
  47663. this.beta += this.inertialBetaOffset;
  47664. this.radius -= this.inertialRadiusOffset;
  47665. this.inertialAlphaOffset *= this.inertia;
  47666. this.inertialBetaOffset *= this.inertia;
  47667. this.inertialRadiusOffset *= this.inertia;
  47668. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47669. this.inertialAlphaOffset = 0;
  47670. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47671. this.inertialBetaOffset = 0;
  47672. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47673. this.inertialRadiusOffset = 0;
  47674. }
  47675. // Panning inertia
  47676. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47677. if (!this._localDirection) {
  47678. this._localDirection = BABYLON.Vector3.Zero();
  47679. this._transformedDirection = BABYLON.Vector3.Zero();
  47680. }
  47681. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47682. this._localDirection.multiplyInPlace(this.panningAxis);
  47683. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47684. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47685. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47686. if (!this.panningAxis.y) {
  47687. this._transformedDirection.y = 0;
  47688. }
  47689. if (!this._targetHost) {
  47690. if (this.panningDistanceLimit) {
  47691. this._transformedDirection.addInPlace(this._target);
  47692. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47693. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47694. this._target.copyFrom(this._transformedDirection);
  47695. }
  47696. }
  47697. else {
  47698. this._target.addInPlace(this._transformedDirection);
  47699. }
  47700. }
  47701. this.inertialPanningX *= this.panningInertia;
  47702. this.inertialPanningY *= this.panningInertia;
  47703. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47704. this.inertialPanningX = 0;
  47705. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47706. this.inertialPanningY = 0;
  47707. }
  47708. // Limits
  47709. this._checkLimits();
  47710. _super.prototype._checkInputs.call(this);
  47711. };
  47712. ArcRotateCamera.prototype._checkLimits = function () {
  47713. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47714. if (this.allowUpsideDown && this.beta > Math.PI) {
  47715. this.beta = this.beta - (2 * Math.PI);
  47716. }
  47717. }
  47718. else {
  47719. if (this.beta < this.lowerBetaLimit) {
  47720. this.beta = this.lowerBetaLimit;
  47721. }
  47722. }
  47723. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47724. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47725. this.beta = this.beta + (2 * Math.PI);
  47726. }
  47727. }
  47728. else {
  47729. if (this.beta > this.upperBetaLimit) {
  47730. this.beta = this.upperBetaLimit;
  47731. }
  47732. }
  47733. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47734. this.alpha = this.lowerAlphaLimit;
  47735. }
  47736. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47737. this.alpha = this.upperAlphaLimit;
  47738. }
  47739. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47740. this.radius = this.lowerRadiusLimit;
  47741. }
  47742. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47743. this.radius = this.upperRadiusLimit;
  47744. }
  47745. };
  47746. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47747. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47748. this.radius = this._computationVector.length();
  47749. if (this.radius === 0) {
  47750. this.radius = 0.0001; // Just to avoid division by zero
  47751. }
  47752. // Alpha
  47753. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47754. if (this._computationVector.z < 0) {
  47755. this.alpha = 2 * Math.PI - this.alpha;
  47756. }
  47757. // Beta
  47758. this.beta = Math.acos(this._computationVector.y / this.radius);
  47759. this._checkLimits();
  47760. };
  47761. ArcRotateCamera.prototype.setPosition = function (position) {
  47762. if (this.position.equals(position)) {
  47763. return;
  47764. }
  47765. this.position.copyFrom(position);
  47766. this.rebuildAnglesAndRadius();
  47767. };
  47768. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47769. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47770. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47771. if (target.getBoundingInfo) {
  47772. if (toBoundingCenter) {
  47773. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47774. }
  47775. else {
  47776. this._targetBoundingCenter = null;
  47777. }
  47778. this._targetHost = target;
  47779. this._target = this._getTargetPosition();
  47780. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47781. }
  47782. else {
  47783. var newTarget = target;
  47784. var currentTarget = this._getTargetPosition();
  47785. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47786. return;
  47787. }
  47788. this._targetHost = null;
  47789. this._target = newTarget;
  47790. this._targetBoundingCenter = null;
  47791. this.onMeshTargetChangedObservable.notifyObservers(null);
  47792. }
  47793. this.rebuildAnglesAndRadius();
  47794. };
  47795. ArcRotateCamera.prototype._getViewMatrix = function () {
  47796. // Compute
  47797. var cosa = Math.cos(this.alpha);
  47798. var sina = Math.sin(this.alpha);
  47799. var cosb = Math.cos(this.beta);
  47800. var sinb = Math.sin(this.beta);
  47801. if (sinb === 0) {
  47802. sinb = 0.0001;
  47803. }
  47804. var target = this._getTargetPosition();
  47805. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47806. target.addToRef(this._computationVector, this._newPosition);
  47807. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47808. if (!this._collider) {
  47809. this._collider = new BABYLON.Collider();
  47810. }
  47811. this._collider._radius = this.collisionRadius;
  47812. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47813. this._collisionTriggered = true;
  47814. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47815. }
  47816. else {
  47817. this.position.copyFrom(this._newPosition);
  47818. var up = this.upVector;
  47819. if (this.allowUpsideDown && sinb < 0) {
  47820. up = up.clone();
  47821. up = up.negate();
  47822. }
  47823. if (this.getScene().useRightHandedSystem) {
  47824. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  47825. }
  47826. else {
  47827. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  47828. }
  47829. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47830. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47831. }
  47832. this._currentTarget = target;
  47833. return this._viewMatrix;
  47834. };
  47835. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47836. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47837. meshes = meshes || this.getScene().meshes;
  47838. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47839. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47840. this.radius = distance * this.zoomOnFactor;
  47841. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47842. };
  47843. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47844. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47845. var meshesOrMinMaxVector;
  47846. var distance;
  47847. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  47848. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47849. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47850. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47851. }
  47852. else {
  47853. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47854. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47855. distance = minMaxVectorAndDistance.distance;
  47856. }
  47857. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47858. if (!doNotUpdateMaxZ) {
  47859. this.maxZ = distance * 2;
  47860. }
  47861. };
  47862. /**
  47863. * @override
  47864. * Override Camera.createRigCamera
  47865. */
  47866. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47867. var alphaShift = 0;
  47868. switch (this.cameraRigMode) {
  47869. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47872. case BABYLON.Camera.RIG_MODE_VR:
  47873. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47874. break;
  47875. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47876. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47877. break;
  47878. }
  47879. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47880. rigCam._cameraRigParams = {};
  47881. return rigCam;
  47882. };
  47883. /**
  47884. * @override
  47885. * Override Camera._updateRigCameras
  47886. */
  47887. ArcRotateCamera.prototype._updateRigCameras = function () {
  47888. var camLeft = this._rigCameras[0];
  47889. var camRight = this._rigCameras[1];
  47890. camLeft.beta = camRight.beta = this.beta;
  47891. camLeft.radius = camRight.radius = this.radius;
  47892. switch (this.cameraRigMode) {
  47893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47896. case BABYLON.Camera.RIG_MODE_VR:
  47897. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47898. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47899. break;
  47900. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47901. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47902. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47903. break;
  47904. }
  47905. _super.prototype._updateRigCameras.call(this);
  47906. };
  47907. ArcRotateCamera.prototype.dispose = function () {
  47908. this.inputs.clear();
  47909. _super.prototype.dispose.call(this);
  47910. };
  47911. ArcRotateCamera.prototype.getClassName = function () {
  47912. return "ArcRotateCamera";
  47913. };
  47914. __decorate([
  47915. BABYLON.serialize()
  47916. ], ArcRotateCamera.prototype, "alpha", void 0);
  47917. __decorate([
  47918. BABYLON.serialize()
  47919. ], ArcRotateCamera.prototype, "beta", void 0);
  47920. __decorate([
  47921. BABYLON.serialize()
  47922. ], ArcRotateCamera.prototype, "radius", void 0);
  47923. __decorate([
  47924. BABYLON.serializeAsVector3("target")
  47925. ], ArcRotateCamera.prototype, "_target", void 0);
  47926. __decorate([
  47927. BABYLON.serialize()
  47928. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47929. __decorate([
  47930. BABYLON.serialize()
  47931. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47932. __decorate([
  47933. BABYLON.serialize()
  47934. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47935. __decorate([
  47936. BABYLON.serialize()
  47937. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47938. __decorate([
  47939. BABYLON.serialize()
  47940. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47941. __decorate([
  47942. BABYLON.serialize()
  47943. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47944. __decorate([
  47945. BABYLON.serialize()
  47946. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47947. __decorate([
  47948. BABYLON.serialize()
  47949. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47950. __decorate([
  47951. BABYLON.serialize()
  47952. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47953. __decorate([
  47954. BABYLON.serialize()
  47955. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47956. __decorate([
  47957. BABYLON.serialize()
  47958. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47959. __decorate([
  47960. BABYLON.serialize()
  47961. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47962. __decorate([
  47963. BABYLON.serialize()
  47964. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47965. __decorate([
  47966. BABYLON.serializeAsVector3()
  47967. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47968. __decorate([
  47969. BABYLON.serialize()
  47970. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47971. __decorate([
  47972. BABYLON.serialize()
  47973. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47974. __decorate([
  47975. BABYLON.serialize()
  47976. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47977. return ArcRotateCamera;
  47978. }(BABYLON.TargetCamera));
  47979. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47980. })(BABYLON || (BABYLON = {}));
  47981. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47982. "use strict";
  47983. var BABYLON;
  47984. (function (BABYLON) {
  47985. /**
  47986. * The HemisphericLight simulates the ambient environment light,
  47987. * so the passed direction is the light reflection direction, not the incoming direction.
  47988. */
  47989. var HemisphericLight = /** @class */ (function (_super) {
  47990. __extends(HemisphericLight, _super);
  47991. /**
  47992. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47993. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47994. * The HemisphericLight can't cast shadows.
  47995. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47996. * @param name The friendly name of the light
  47997. * @param direction The direction of the light reflection
  47998. * @param scene The scene the light belongs to
  47999. */
  48000. function HemisphericLight(name, direction, scene) {
  48001. var _this = _super.call(this, name, scene) || this;
  48002. /**
  48003. * The groundColor is the light in the opposite direction to the one specified during creation.
  48004. * 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.
  48005. */
  48006. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48007. _this.direction = direction || BABYLON.Vector3.Up();
  48008. return _this;
  48009. }
  48010. HemisphericLight.prototype._buildUniformLayout = function () {
  48011. this._uniformBuffer.addUniform("vLightData", 4);
  48012. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48013. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48014. this._uniformBuffer.addUniform("vLightGround", 3);
  48015. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48016. this._uniformBuffer.addUniform("depthValues", 2);
  48017. this._uniformBuffer.create();
  48018. };
  48019. /**
  48020. * Returns the string "HemisphericLight".
  48021. * @return The class name
  48022. */
  48023. HemisphericLight.prototype.getClassName = function () {
  48024. return "HemisphericLight";
  48025. };
  48026. /**
  48027. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48028. * Returns the updated direction.
  48029. * @param target The target the direction should point to
  48030. * @return The computed direction
  48031. */
  48032. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48033. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48034. return this.direction;
  48035. };
  48036. /**
  48037. * Returns the shadow generator associated to the light.
  48038. * @returns Always null for hemispheric lights because it does not support shadows.
  48039. */
  48040. HemisphericLight.prototype.getShadowGenerator = function () {
  48041. return null;
  48042. };
  48043. /**
  48044. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48045. * @param effect The effect to update
  48046. * @param lightIndex The index of the light in the effect to update
  48047. * @returns The hemispheric light
  48048. */
  48049. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48050. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48051. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48052. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48053. return this;
  48054. };
  48055. /**
  48056. * @ignore internal use only.
  48057. */
  48058. HemisphericLight.prototype._getWorldMatrix = function () {
  48059. if (!this._worldMatrix) {
  48060. this._worldMatrix = BABYLON.Matrix.Identity();
  48061. }
  48062. return this._worldMatrix;
  48063. };
  48064. /**
  48065. * Returns the integer 3.
  48066. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48067. */
  48068. HemisphericLight.prototype.getTypeID = function () {
  48069. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48070. };
  48071. __decorate([
  48072. BABYLON.serializeAsColor3()
  48073. ], HemisphericLight.prototype, "groundColor", void 0);
  48074. __decorate([
  48075. BABYLON.serializeAsVector3()
  48076. ], HemisphericLight.prototype, "direction", void 0);
  48077. return HemisphericLight;
  48078. }(BABYLON.Light));
  48079. BABYLON.HemisphericLight = HemisphericLight;
  48080. })(BABYLON || (BABYLON = {}));
  48081. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48082. "use strict";
  48083. var BABYLON;
  48084. (function (BABYLON) {
  48085. /**
  48086. * Base implementation IShadowLight
  48087. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48088. */
  48089. var ShadowLight = /** @class */ (function (_super) {
  48090. __extends(ShadowLight, _super);
  48091. function ShadowLight() {
  48092. var _this = _super !== null && _super.apply(this, arguments) || this;
  48093. _this._needProjectionMatrixCompute = true;
  48094. return _this;
  48095. }
  48096. ShadowLight.prototype._setPosition = function (value) {
  48097. this._position = value;
  48098. };
  48099. Object.defineProperty(ShadowLight.prototype, "position", {
  48100. /**
  48101. * Sets the position the shadow will be casted from. Also use as the light position for both
  48102. * point and spot lights.
  48103. */
  48104. get: function () {
  48105. return this._position;
  48106. },
  48107. /**
  48108. * Sets the position the shadow will be casted from. Also use as the light position for both
  48109. * point and spot lights.
  48110. */
  48111. set: function (value) {
  48112. this._setPosition(value);
  48113. },
  48114. enumerable: true,
  48115. configurable: true
  48116. });
  48117. ShadowLight.prototype._setDirection = function (value) {
  48118. this._direction = value;
  48119. };
  48120. Object.defineProperty(ShadowLight.prototype, "direction", {
  48121. /**
  48122. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48123. * Also use as the light direction on spot and directional lights.
  48124. */
  48125. get: function () {
  48126. return this._direction;
  48127. },
  48128. /**
  48129. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48130. * Also use as the light direction on spot and directional lights.
  48131. */
  48132. set: function (value) {
  48133. this._setDirection(value);
  48134. },
  48135. enumerable: true,
  48136. configurable: true
  48137. });
  48138. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48139. /**
  48140. * Gets the shadow projection clipping minimum z value.
  48141. */
  48142. get: function () {
  48143. return this._shadowMinZ;
  48144. },
  48145. /**
  48146. * Sets the shadow projection clipping minimum z value.
  48147. */
  48148. set: function (value) {
  48149. this._shadowMinZ = value;
  48150. this.forceProjectionMatrixCompute();
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48156. /**
  48157. * Sets the shadow projection clipping maximum z value.
  48158. */
  48159. get: function () {
  48160. return this._shadowMaxZ;
  48161. },
  48162. /**
  48163. * Gets the shadow projection clipping maximum z value.
  48164. */
  48165. set: function (value) {
  48166. this._shadowMaxZ = value;
  48167. this.forceProjectionMatrixCompute();
  48168. },
  48169. enumerable: true,
  48170. configurable: true
  48171. });
  48172. /**
  48173. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48174. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48175. */
  48176. ShadowLight.prototype.computeTransformedInformation = function () {
  48177. if (this.parent && this.parent.getWorldMatrix) {
  48178. if (!this.transformedPosition) {
  48179. this.transformedPosition = BABYLON.Vector3.Zero();
  48180. }
  48181. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48182. // In case the direction is present.
  48183. if (this.direction) {
  48184. if (!this.transformedDirection) {
  48185. this.transformedDirection = BABYLON.Vector3.Zero();
  48186. }
  48187. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48188. }
  48189. return true;
  48190. }
  48191. return false;
  48192. };
  48193. /**
  48194. * Return the depth scale used for the shadow map.
  48195. * @returns the depth scale.
  48196. */
  48197. ShadowLight.prototype.getDepthScale = function () {
  48198. return 50.0;
  48199. };
  48200. /**
  48201. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48202. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48203. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48204. */
  48205. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48206. return this.transformedDirection ? this.transformedDirection : this.direction;
  48207. };
  48208. /**
  48209. * Returns the ShadowLight absolute position in the World.
  48210. * @returns the position vector in world space
  48211. */
  48212. ShadowLight.prototype.getAbsolutePosition = function () {
  48213. return this.transformedPosition ? this.transformedPosition : this.position;
  48214. };
  48215. /**
  48216. * Sets the ShadowLight direction toward the passed target.
  48217. * @param target The point tot target in local space
  48218. * @returns the updated ShadowLight direction
  48219. */
  48220. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48221. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48222. return this.direction;
  48223. };
  48224. /**
  48225. * Returns the light rotation in euler definition.
  48226. * @returns the x y z rotation in local space.
  48227. */
  48228. ShadowLight.prototype.getRotation = function () {
  48229. this.direction.normalize();
  48230. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48231. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48232. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48233. };
  48234. /**
  48235. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48236. * @returns true if a cube texture needs to be use
  48237. */
  48238. ShadowLight.prototype.needCube = function () {
  48239. return false;
  48240. };
  48241. /**
  48242. * Detects if the projection matrix requires to be recomputed this frame.
  48243. * @returns true if it requires to be recomputed otherwise, false.
  48244. */
  48245. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48246. return this._needProjectionMatrixCompute;
  48247. };
  48248. /**
  48249. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48250. */
  48251. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48252. this._needProjectionMatrixCompute = true;
  48253. };
  48254. /**
  48255. * Get the world matrix of the sahdow lights.
  48256. * @ignore Internal Use Only
  48257. */
  48258. ShadowLight.prototype._getWorldMatrix = function () {
  48259. if (!this._worldMatrix) {
  48260. this._worldMatrix = BABYLON.Matrix.Identity();
  48261. }
  48262. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48263. return this._worldMatrix;
  48264. };
  48265. /**
  48266. * Gets the minZ used for shadow according to both the scene and the light.
  48267. * @param activeCamera The camera we are returning the min for
  48268. * @returns the depth min z
  48269. */
  48270. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48271. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48272. };
  48273. /**
  48274. * Gets the maxZ used for shadow according to both the scene and the light.
  48275. * @param activeCamera The camera we are returning the max for
  48276. * @returns the depth max z
  48277. */
  48278. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48279. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48280. };
  48281. /**
  48282. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48283. * @param matrix The materix to updated with the projection information
  48284. * @param viewMatrix The transform matrix of the light
  48285. * @param renderList The list of mesh to render in the map
  48286. * @returns The current light
  48287. */
  48288. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48289. if (this.customProjectionMatrixBuilder) {
  48290. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48291. }
  48292. else {
  48293. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48294. }
  48295. return this;
  48296. };
  48297. __decorate([
  48298. BABYLON.serializeAsVector3()
  48299. ], ShadowLight.prototype, "position", null);
  48300. __decorate([
  48301. BABYLON.serializeAsVector3()
  48302. ], ShadowLight.prototype, "direction", null);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ShadowLight.prototype, "shadowMinZ", null);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ShadowLight.prototype, "shadowMaxZ", null);
  48309. return ShadowLight;
  48310. }(BABYLON.Light));
  48311. BABYLON.ShadowLight = ShadowLight;
  48312. })(BABYLON || (BABYLON = {}));
  48313. //# sourceMappingURL=babylon.shadowLight.js.map
  48314. "use strict";
  48315. var BABYLON;
  48316. (function (BABYLON) {
  48317. /**
  48318. * A point light is a light defined by an unique point in world space.
  48319. * The light is emitted in every direction from this point.
  48320. * A good example of a point light is a standard light bulb.
  48321. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48322. */
  48323. var PointLight = /** @class */ (function (_super) {
  48324. __extends(PointLight, _super);
  48325. /**
  48326. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48327. * A PointLight emits the light in every direction.
  48328. * It can cast shadows.
  48329. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48330. * ```javascript
  48331. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48332. * ```
  48333. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48334. * @param name The light friendly name
  48335. * @param position The position of the point light in the scene
  48336. * @param scene The scene the lights belongs to
  48337. */
  48338. function PointLight(name, position, scene) {
  48339. var _this = _super.call(this, name, scene) || this;
  48340. _this._shadowAngle = Math.PI / 2;
  48341. _this.position = position;
  48342. return _this;
  48343. }
  48344. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48345. /**
  48346. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48347. * This specifies what angle the shadow will use to be created.
  48348. *
  48349. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48350. */
  48351. get: function () {
  48352. return this._shadowAngle;
  48353. },
  48354. /**
  48355. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48356. * This specifies what angle the shadow will use to be created.
  48357. *
  48358. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48359. */
  48360. set: function (value) {
  48361. this._shadowAngle = value;
  48362. this.forceProjectionMatrixCompute();
  48363. },
  48364. enumerable: true,
  48365. configurable: true
  48366. });
  48367. Object.defineProperty(PointLight.prototype, "direction", {
  48368. /**
  48369. * Gets the direction if it has been set.
  48370. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48371. */
  48372. get: function () {
  48373. return this._direction;
  48374. },
  48375. /**
  48376. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48377. */
  48378. set: function (value) {
  48379. var previousNeedCube = this.needCube();
  48380. this._direction = value;
  48381. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48382. this._shadowGenerator.recreateShadowMap();
  48383. }
  48384. },
  48385. enumerable: true,
  48386. configurable: true
  48387. });
  48388. /**
  48389. * Returns the string "PointLight"
  48390. * @returns the class name
  48391. */
  48392. PointLight.prototype.getClassName = function () {
  48393. return "PointLight";
  48394. };
  48395. /**
  48396. * Returns the integer 0.
  48397. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48398. */
  48399. PointLight.prototype.getTypeID = function () {
  48400. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48401. };
  48402. /**
  48403. * Specifies wether or not the shadowmap should be a cube texture.
  48404. * @returns true if the shadowmap needs to be a cube texture.
  48405. */
  48406. PointLight.prototype.needCube = function () {
  48407. return !this.direction;
  48408. };
  48409. /**
  48410. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48411. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48412. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48413. */
  48414. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48415. if (this.direction) {
  48416. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48417. }
  48418. else {
  48419. switch (faceIndex) {
  48420. case 0:
  48421. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48422. case 1:
  48423. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48424. case 2:
  48425. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48426. case 3:
  48427. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48428. case 4:
  48429. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48430. case 5:
  48431. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48432. }
  48433. }
  48434. return BABYLON.Vector3.Zero();
  48435. };
  48436. /**
  48437. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48438. * - fov = PI / 2
  48439. * - aspect ratio : 1.0
  48440. * - z-near and far equal to the active camera minZ and maxZ.
  48441. * Returns the PointLight.
  48442. */
  48443. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48444. var activeCamera = this.getScene().activeCamera;
  48445. if (!activeCamera) {
  48446. return;
  48447. }
  48448. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48449. };
  48450. PointLight.prototype._buildUniformLayout = function () {
  48451. this._uniformBuffer.addUniform("vLightData", 4);
  48452. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48453. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48454. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48455. this._uniformBuffer.addUniform("depthValues", 2);
  48456. this._uniformBuffer.create();
  48457. };
  48458. /**
  48459. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48460. * @param effect The effect to update
  48461. * @param lightIndex The index of the light in the effect to update
  48462. * @returns The point light
  48463. */
  48464. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48465. if (this.computeTransformedInformation()) {
  48466. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48467. return this;
  48468. }
  48469. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48470. return this;
  48471. };
  48472. __decorate([
  48473. BABYLON.serialize()
  48474. ], PointLight.prototype, "shadowAngle", null);
  48475. return PointLight;
  48476. }(BABYLON.ShadowLight));
  48477. BABYLON.PointLight = PointLight;
  48478. })(BABYLON || (BABYLON = {}));
  48479. //# sourceMappingURL=babylon.pointLight.js.map
  48480. "use strict";
  48481. var BABYLON;
  48482. (function (BABYLON) {
  48483. /**
  48484. * A directional light is defined by a direction (what a surprise!).
  48485. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48486. * 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.
  48487. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48488. */
  48489. var DirectionalLight = /** @class */ (function (_super) {
  48490. __extends(DirectionalLight, _super);
  48491. /**
  48492. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48493. * The directional light is emitted from everywhere in the given direction.
  48494. * It can cast shawdows.
  48495. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48496. * @param name The friendly name of the light
  48497. * @param direction The direction of the light
  48498. * @param scene The scene the light belongs to
  48499. */
  48500. function DirectionalLight(name, direction, scene) {
  48501. var _this = _super.call(this, name, scene) || this;
  48502. _this._shadowFrustumSize = 0;
  48503. _this._shadowOrthoScale = 0.1;
  48504. /**
  48505. * Automatically compute the projection matrix to best fit (including all the casters)
  48506. * on each frame.
  48507. */
  48508. _this.autoUpdateExtends = true;
  48509. // Cache
  48510. _this._orthoLeft = Number.MAX_VALUE;
  48511. _this._orthoRight = Number.MIN_VALUE;
  48512. _this._orthoTop = Number.MIN_VALUE;
  48513. _this._orthoBottom = Number.MAX_VALUE;
  48514. _this.position = direction.scale(-1.0);
  48515. _this.direction = direction;
  48516. return _this;
  48517. }
  48518. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48519. /**
  48520. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48521. */
  48522. get: function () {
  48523. return this._shadowFrustumSize;
  48524. },
  48525. /**
  48526. * Specifies a fix frustum size for the shadow generation.
  48527. */
  48528. set: function (value) {
  48529. this._shadowFrustumSize = value;
  48530. this.forceProjectionMatrixCompute();
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48536. /**
  48537. * Gets the shadow projection scale against the optimal computed one.
  48538. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48539. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48540. */
  48541. get: function () {
  48542. return this._shadowOrthoScale;
  48543. },
  48544. /**
  48545. * Sets the shadow projection scale against the optimal computed one.
  48546. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48547. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48548. */
  48549. set: function (value) {
  48550. this._shadowOrthoScale = value;
  48551. this.forceProjectionMatrixCompute();
  48552. },
  48553. enumerable: true,
  48554. configurable: true
  48555. });
  48556. /**
  48557. * Returns the string "DirectionalLight".
  48558. * @return The class name
  48559. */
  48560. DirectionalLight.prototype.getClassName = function () {
  48561. return "DirectionalLight";
  48562. };
  48563. /**
  48564. * Returns the integer 1.
  48565. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48566. */
  48567. DirectionalLight.prototype.getTypeID = function () {
  48568. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48569. };
  48570. /**
  48571. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48572. * Returns the DirectionalLight Shadow projection matrix.
  48573. */
  48574. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48575. if (this.shadowFrustumSize > 0) {
  48576. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48577. }
  48578. else {
  48579. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48580. }
  48581. };
  48582. /**
  48583. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48584. * Returns the DirectionalLight Shadow projection matrix.
  48585. */
  48586. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48587. var activeCamera = this.getScene().activeCamera;
  48588. if (!activeCamera) {
  48589. return;
  48590. }
  48591. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48592. };
  48593. /**
  48594. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48595. * Returns the DirectionalLight Shadow projection matrix.
  48596. */
  48597. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48598. var activeCamera = this.getScene().activeCamera;
  48599. if (!activeCamera) {
  48600. return;
  48601. }
  48602. // Check extends
  48603. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48604. var tempVector3 = BABYLON.Vector3.Zero();
  48605. this._orthoLeft = Number.MAX_VALUE;
  48606. this._orthoRight = Number.MIN_VALUE;
  48607. this._orthoTop = Number.MIN_VALUE;
  48608. this._orthoBottom = Number.MAX_VALUE;
  48609. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48610. var mesh = renderList[meshIndex];
  48611. if (!mesh) {
  48612. continue;
  48613. }
  48614. var boundingInfo = mesh.getBoundingInfo();
  48615. var boundingBox = boundingInfo.boundingBox;
  48616. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48617. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48618. if (tempVector3.x < this._orthoLeft)
  48619. this._orthoLeft = tempVector3.x;
  48620. if (tempVector3.y < this._orthoBottom)
  48621. this._orthoBottom = tempVector3.y;
  48622. if (tempVector3.x > this._orthoRight)
  48623. this._orthoRight = tempVector3.x;
  48624. if (tempVector3.y > this._orthoTop)
  48625. this._orthoTop = tempVector3.y;
  48626. }
  48627. }
  48628. }
  48629. var xOffset = this._orthoRight - this._orthoLeft;
  48630. var yOffset = this._orthoTop - this._orthoBottom;
  48631. 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);
  48632. };
  48633. DirectionalLight.prototype._buildUniformLayout = function () {
  48634. this._uniformBuffer.addUniform("vLightData", 4);
  48635. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48636. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48637. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48638. this._uniformBuffer.addUniform("depthValues", 2);
  48639. this._uniformBuffer.create();
  48640. };
  48641. /**
  48642. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48643. * @param effect The effect to update
  48644. * @param lightIndex The index of the light in the effect to update
  48645. * @returns The directional light
  48646. */
  48647. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48648. if (this.computeTransformedInformation()) {
  48649. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48650. return this;
  48651. }
  48652. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48653. return this;
  48654. };
  48655. /**
  48656. * Gets the minZ used for shadow according to both the scene and the light.
  48657. *
  48658. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48659. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48660. * @param activeCamera The camera we are returning the min for
  48661. * @returns the depth min z
  48662. */
  48663. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48664. return 1;
  48665. };
  48666. /**
  48667. * Gets the maxZ used for shadow according to both the scene and the light.
  48668. *
  48669. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48670. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48671. * @param activeCamera The camera we are returning the max for
  48672. * @returns the depth max z
  48673. */
  48674. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48675. return 1;
  48676. };
  48677. __decorate([
  48678. BABYLON.serialize()
  48679. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48680. __decorate([
  48681. BABYLON.serialize()
  48682. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48683. __decorate([
  48684. BABYLON.serialize()
  48685. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48686. return DirectionalLight;
  48687. }(BABYLON.ShadowLight));
  48688. BABYLON.DirectionalLight = DirectionalLight;
  48689. })(BABYLON || (BABYLON = {}));
  48690. //# sourceMappingURL=babylon.directionalLight.js.map
  48691. "use strict";
  48692. var BABYLON;
  48693. (function (BABYLON) {
  48694. /**
  48695. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48696. * These values define a cone of light starting from the position, emitting toward the direction.
  48697. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48698. * and the exponent defines the speed of the decay of the light with distance (reach).
  48699. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48700. */
  48701. var SpotLight = /** @class */ (function (_super) {
  48702. __extends(SpotLight, _super);
  48703. /**
  48704. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48705. * It can cast shadows.
  48706. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48707. * @param name The light friendly name
  48708. * @param position The position of the spot light in the scene
  48709. * @param direction The direction of the light in the scene
  48710. * @param angle The cone angle of the light in Radians
  48711. * @param exponent The light decay speed with the distance from the emission spot
  48712. * @param scene The scene the lights belongs to
  48713. */
  48714. function SpotLight(name, position, direction, angle, exponent, scene) {
  48715. var _this = _super.call(this, name, scene) || this;
  48716. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48717. _this._projectionTextureLightNear = 1e-6;
  48718. _this._projectionTextureLightFar = 1000.0;
  48719. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48720. _this._projectionTextureViewLightDirty = true;
  48721. _this._projectionTextureProjectionLightDirty = true;
  48722. _this._projectionTextureDirty = true;
  48723. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48724. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48725. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48726. _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);
  48727. _this.position = position;
  48728. _this.direction = direction;
  48729. _this.angle = angle;
  48730. _this.exponent = exponent;
  48731. return _this;
  48732. }
  48733. Object.defineProperty(SpotLight.prototype, "angle", {
  48734. /**
  48735. * Gets the cone angle of the spot light in Radians.
  48736. */
  48737. get: function () {
  48738. return this._angle;
  48739. },
  48740. /**
  48741. * Sets the cone angle of the spot light in Radians.
  48742. */
  48743. set: function (value) {
  48744. this._angle = value;
  48745. this._projectionTextureProjectionLightDirty = true;
  48746. this.forceProjectionMatrixCompute();
  48747. },
  48748. enumerable: true,
  48749. configurable: true
  48750. });
  48751. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48752. /**
  48753. * Allows scaling the angle of the light for shadow generation only.
  48754. */
  48755. get: function () {
  48756. return this._shadowAngleScale;
  48757. },
  48758. /**
  48759. * Allows scaling the angle of the light for shadow generation only.
  48760. */
  48761. set: function (value) {
  48762. this._shadowAngleScale = value;
  48763. this.forceProjectionMatrixCompute();
  48764. },
  48765. enumerable: true,
  48766. configurable: true
  48767. });
  48768. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48769. /**
  48770. * Allows reading the projecton texture
  48771. */
  48772. get: function () {
  48773. return this._projectionTextureMatrix;
  48774. },
  48775. enumerable: true,
  48776. configurable: true
  48777. });
  48778. ;
  48779. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48780. /**
  48781. * Gets the near clip of the Spotlight for texture projection.
  48782. */
  48783. get: function () {
  48784. return this._projectionTextureLightNear;
  48785. },
  48786. /**
  48787. * Sets the near clip of the Spotlight for texture projection.
  48788. */
  48789. set: function (value) {
  48790. this._projectionTextureLightNear = value;
  48791. this._projectionTextureProjectionLightDirty = true;
  48792. },
  48793. enumerable: true,
  48794. configurable: true
  48795. });
  48796. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48797. /**
  48798. * Gets the far clip of the Spotlight for texture projection.
  48799. */
  48800. get: function () {
  48801. return this._projectionTextureLightFar;
  48802. },
  48803. /**
  48804. * Sets the far clip of the Spotlight for texture projection.
  48805. */
  48806. set: function (value) {
  48807. this._projectionTextureLightFar = value;
  48808. this._projectionTextureProjectionLightDirty = true;
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48814. /**
  48815. * Gets the Up vector of the Spotlight for texture projection.
  48816. */
  48817. get: function () {
  48818. return this._projectionTextureUpDirection;
  48819. },
  48820. /**
  48821. * Sets the Up vector of the Spotlight for texture projection.
  48822. */
  48823. set: function (value) {
  48824. this._projectionTextureUpDirection = value;
  48825. this._projectionTextureProjectionLightDirty = true;
  48826. },
  48827. enumerable: true,
  48828. configurable: true
  48829. });
  48830. ;
  48831. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48832. /**
  48833. * Gets the projection texture of the light.
  48834. */
  48835. get: function () {
  48836. return this._projectionTexture;
  48837. },
  48838. /**
  48839. * Sets the projection texture of the light.
  48840. */
  48841. set: function (value) {
  48842. this._projectionTexture = value;
  48843. this._projectionTextureDirty = true;
  48844. },
  48845. enumerable: true,
  48846. configurable: true
  48847. });
  48848. /**
  48849. * Returns the string "SpotLight".
  48850. * @returns the class name
  48851. */
  48852. SpotLight.prototype.getClassName = function () {
  48853. return "SpotLight";
  48854. };
  48855. /**
  48856. * Returns the integer 2.
  48857. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48858. */
  48859. SpotLight.prototype.getTypeID = function () {
  48860. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48861. };
  48862. /**
  48863. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48864. */
  48865. SpotLight.prototype._setDirection = function (value) {
  48866. _super.prototype._setDirection.call(this, value);
  48867. this._projectionTextureViewLightDirty = true;
  48868. };
  48869. /**
  48870. * Overrides the position setter to recompute the projection texture view light Matrix.
  48871. */
  48872. SpotLight.prototype._setPosition = function (value) {
  48873. _super.prototype._setPosition.call(this, value);
  48874. this._projectionTextureViewLightDirty = true;
  48875. };
  48876. /**
  48877. * 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.
  48878. * Returns the SpotLight.
  48879. */
  48880. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48881. var activeCamera = this.getScene().activeCamera;
  48882. if (!activeCamera) {
  48883. return;
  48884. }
  48885. this._shadowAngleScale = this._shadowAngleScale || 1;
  48886. var angle = this._shadowAngleScale * this._angle;
  48887. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48888. };
  48889. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48890. this._projectionTextureViewLightDirty = false;
  48891. this._projectionTextureDirty = true;
  48892. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48893. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48894. };
  48895. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48896. this._projectionTextureProjectionLightDirty = false;
  48897. this._projectionTextureDirty = true;
  48898. var light_far = this.projectionTextureLightFar;
  48899. var light_near = this.projectionTextureLightNear;
  48900. var P = light_far / (light_far - light_near);
  48901. var Q = -P * light_near;
  48902. var S = 1.0 / Math.tan(this._angle / 2.0);
  48903. var A = 1.0;
  48904. 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);
  48905. };
  48906. /**
  48907. * Main function for light texture projection matrix computing.
  48908. */
  48909. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48910. this._projectionTextureDirty = false;
  48911. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48912. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48913. };
  48914. SpotLight.prototype._buildUniformLayout = function () {
  48915. this._uniformBuffer.addUniform("vLightData", 4);
  48916. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48917. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48918. this._uniformBuffer.addUniform("vLightDirection", 3);
  48919. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48920. this._uniformBuffer.addUniform("depthValues", 2);
  48921. this._uniformBuffer.create();
  48922. };
  48923. /**
  48924. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48925. * @param effect The effect to update
  48926. * @param lightIndex The index of the light in the effect to update
  48927. * @returns The spot light
  48928. */
  48929. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48930. var normalizeDirection;
  48931. if (this.computeTransformedInformation()) {
  48932. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48933. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48934. }
  48935. else {
  48936. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48937. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48938. }
  48939. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48940. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48941. if (this._projectionTextureViewLightDirty) {
  48942. this._computeProjectionTextureViewLightMatrix();
  48943. }
  48944. if (this._projectionTextureProjectionLightDirty) {
  48945. this._computeProjectionTextureProjectionLightMatrix();
  48946. }
  48947. if (this._projectionTextureDirty) {
  48948. this._computeProjectionTextureMatrix();
  48949. }
  48950. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48951. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48952. }
  48953. return this;
  48954. };
  48955. /**
  48956. * Disposes the light and the associated resources.
  48957. */
  48958. SpotLight.prototype.dispose = function () {
  48959. _super.prototype.dispose.call(this);
  48960. if (this._projectionTexture) {
  48961. this._projectionTexture.dispose();
  48962. }
  48963. };
  48964. __decorate([
  48965. BABYLON.serialize()
  48966. ], SpotLight.prototype, "angle", null);
  48967. __decorate([
  48968. BABYLON.serialize()
  48969. ], SpotLight.prototype, "shadowAngleScale", null);
  48970. __decorate([
  48971. BABYLON.serialize()
  48972. ], SpotLight.prototype, "exponent", void 0);
  48973. __decorate([
  48974. BABYLON.serialize()
  48975. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48976. __decorate([
  48977. BABYLON.serialize()
  48978. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48979. __decorate([
  48980. BABYLON.serialize()
  48981. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48982. __decorate([
  48983. BABYLON.serializeAsTexture("projectedLightTexture")
  48984. ], SpotLight.prototype, "_projectionTexture", void 0);
  48985. return SpotLight;
  48986. }(BABYLON.ShadowLight));
  48987. BABYLON.SpotLight = SpotLight;
  48988. })(BABYLON || (BABYLON = {}));
  48989. //# sourceMappingURL=babylon.spotLight.js.map
  48990. "use strict";
  48991. var BABYLON;
  48992. (function (BABYLON) {
  48993. /**
  48994. * Class used to override all child animations of a given target
  48995. */
  48996. var AnimationPropertiesOverride = /** @class */ (function () {
  48997. function AnimationPropertiesOverride() {
  48998. /**
  48999. * Gets or sets a value indicating if animation blending must be used
  49000. */
  49001. this.enableBlending = false;
  49002. /**
  49003. * Gets or sets the blending speed to use when enableBlending is true
  49004. */
  49005. this.blendingSpeed = 0.01;
  49006. /**
  49007. * Gets or sets the default loop mode to use
  49008. */
  49009. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49010. }
  49011. return AnimationPropertiesOverride;
  49012. }());
  49013. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49014. })(BABYLON || (BABYLON = {}));
  49015. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49016. "use strict";
  49017. var BABYLON;
  49018. (function (BABYLON) {
  49019. var AnimationRange = /** @class */ (function () {
  49020. function AnimationRange(name, from, to) {
  49021. this.name = name;
  49022. this.from = from;
  49023. this.to = to;
  49024. }
  49025. AnimationRange.prototype.clone = function () {
  49026. return new AnimationRange(this.name, this.from, this.to);
  49027. };
  49028. return AnimationRange;
  49029. }());
  49030. BABYLON.AnimationRange = AnimationRange;
  49031. /**
  49032. * Composed of a frame, and an action function
  49033. */
  49034. var AnimationEvent = /** @class */ (function () {
  49035. function AnimationEvent(frame, action, onlyOnce) {
  49036. this.frame = frame;
  49037. this.action = action;
  49038. this.onlyOnce = onlyOnce;
  49039. this.isDone = false;
  49040. }
  49041. return AnimationEvent;
  49042. }());
  49043. BABYLON.AnimationEvent = AnimationEvent;
  49044. var PathCursor = /** @class */ (function () {
  49045. function PathCursor(path) {
  49046. this.path = path;
  49047. this._onchange = new Array();
  49048. this.value = 0;
  49049. this.animations = new Array();
  49050. }
  49051. PathCursor.prototype.getPoint = function () {
  49052. var point = this.path.getPointAtLengthPosition(this.value);
  49053. return new BABYLON.Vector3(point.x, 0, point.y);
  49054. };
  49055. PathCursor.prototype.moveAhead = function (step) {
  49056. if (step === void 0) { step = 0.002; }
  49057. this.move(step);
  49058. return this;
  49059. };
  49060. PathCursor.prototype.moveBack = function (step) {
  49061. if (step === void 0) { step = 0.002; }
  49062. this.move(-step);
  49063. return this;
  49064. };
  49065. PathCursor.prototype.move = function (step) {
  49066. if (Math.abs(step) > 1) {
  49067. throw "step size should be less than 1.";
  49068. }
  49069. this.value += step;
  49070. this.ensureLimits();
  49071. this.raiseOnChange();
  49072. return this;
  49073. };
  49074. PathCursor.prototype.ensureLimits = function () {
  49075. while (this.value > 1) {
  49076. this.value -= 1;
  49077. }
  49078. while (this.value < 0) {
  49079. this.value += 1;
  49080. }
  49081. return this;
  49082. };
  49083. // used by animation engine
  49084. PathCursor.prototype.raiseOnChange = function () {
  49085. var _this = this;
  49086. this._onchange.forEach(function (f) { return f(_this); });
  49087. return this;
  49088. };
  49089. PathCursor.prototype.onchange = function (f) {
  49090. this._onchange.push(f);
  49091. return this;
  49092. };
  49093. return PathCursor;
  49094. }());
  49095. BABYLON.PathCursor = PathCursor;
  49096. var AnimationKeyInterpolation;
  49097. (function (AnimationKeyInterpolation) {
  49098. /**
  49099. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49100. */
  49101. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49102. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49103. var Animation = /** @class */ (function () {
  49104. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49105. this.name = name;
  49106. this.targetProperty = targetProperty;
  49107. this.framePerSecond = framePerSecond;
  49108. this.dataType = dataType;
  49109. this.loopMode = loopMode;
  49110. this.enableBlending = enableBlending;
  49111. this._runtimeAnimations = new Array();
  49112. // The set of event that will be linked to this animation
  49113. this._events = new Array();
  49114. this.blendingSpeed = 0.01;
  49115. this._ranges = {};
  49116. this.targetPropertyPath = targetProperty.split(".");
  49117. this.dataType = dataType;
  49118. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49119. }
  49120. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49121. var dataType = undefined;
  49122. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49123. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49124. }
  49125. else if (from instanceof BABYLON.Quaternion) {
  49126. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49127. }
  49128. else if (from instanceof BABYLON.Vector3) {
  49129. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49130. }
  49131. else if (from instanceof BABYLON.Vector2) {
  49132. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49133. }
  49134. else if (from instanceof BABYLON.Color3) {
  49135. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49136. }
  49137. else if (from instanceof BABYLON.Size) {
  49138. dataType = Animation.ANIMATIONTYPE_SIZE;
  49139. }
  49140. if (dataType == undefined) {
  49141. return null;
  49142. }
  49143. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49144. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49145. animation.setKeys(keys);
  49146. if (easingFunction !== undefined) {
  49147. animation.setEasingFunction(easingFunction);
  49148. }
  49149. return animation;
  49150. };
  49151. /**
  49152. * Sets up an animation.
  49153. * @param property the property to animate
  49154. * @param animationType the animation type to apply
  49155. * @param easingFunction the easing function used in the animation
  49156. * @returns The created animation
  49157. */
  49158. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49159. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49160. animation.setEasingFunction(easingFunction);
  49161. return animation;
  49162. };
  49163. /**
  49164. * Create and start an animation on a node
  49165. * @param {string} name defines the name of the global animation that will be run on all nodes
  49166. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49167. * @param {string} targetProperty defines property to animate
  49168. * @param {number} framePerSecond defines the number of frame per second yo use
  49169. * @param {number} totalFrame defines the number of frames in total
  49170. * @param {any} from defines the initial value
  49171. * @param {any} to defines the final value
  49172. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49173. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49174. * @param onAnimationEnd defines the callback to call when animation end
  49175. * @returns the animatable created for this animation
  49176. */
  49177. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49178. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49179. if (!animation) {
  49180. return null;
  49181. }
  49182. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49183. };
  49184. /**
  49185. * Create and start an animation on a node and its descendants
  49186. * @param {string} name defines the name of the global animation that will be run on all nodes
  49187. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49188. * @param {boolean} 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.
  49189. * @param {string} targetProperty defines property to animate
  49190. * @param {number} framePerSecond defines the number of frame per second yo use
  49191. * @param {number} totalFrame defines the number of frames in total
  49192. * @param {any} from defines the initial value
  49193. * @param {any} to defines the final value
  49194. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49195. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49196. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49197. * @returns the list of animatables created for all nodes
  49198. * @example https://www.babylonjs-playground.com/#MH0VLI
  49199. */
  49200. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49201. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49202. if (!animation) {
  49203. return null;
  49204. }
  49205. var scene = node.getScene();
  49206. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49207. };
  49208. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49209. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49210. if (!animation) {
  49211. return null;
  49212. }
  49213. node.animations.push(animation);
  49214. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49215. };
  49216. /**
  49217. * Transition property of the Camera to the target Value.
  49218. * @param property The property to transition
  49219. * @param targetValue The target Value of the property
  49220. * @param host The object where the property to animate belongs
  49221. * @param scene Scene used to run the animation
  49222. * @param frameRate Framerate (in frame/s) to use
  49223. * @param transition The transition type we want to use
  49224. * @param duration The duration of the animation, in milliseconds
  49225. * @param onAnimationEnd Call back trigger at the end of the animation.
  49226. */
  49227. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49228. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49229. if (duration <= 0) {
  49230. host[property] = targetValue;
  49231. if (onAnimationEnd) {
  49232. onAnimationEnd();
  49233. }
  49234. return null;
  49235. }
  49236. var endFrame = frameRate * (duration / 1000);
  49237. transition.setKeys([{
  49238. frame: 0,
  49239. value: host[property].clone ? host[property].clone() : host[property]
  49240. },
  49241. {
  49242. frame: endFrame,
  49243. value: targetValue
  49244. }]);
  49245. if (!host.animations) {
  49246. host.animations = [];
  49247. }
  49248. host.animations.push(transition);
  49249. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49250. animation.onAnimationEnd = onAnimationEnd;
  49251. return animation;
  49252. };
  49253. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49254. /**
  49255. * Return the array of runtime animations currently using this animation
  49256. */
  49257. get: function () {
  49258. return this._runtimeAnimations;
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49264. get: function () {
  49265. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49266. var runtimeAnimation = _a[_i];
  49267. if (!runtimeAnimation.isStopped) {
  49268. return true;
  49269. }
  49270. }
  49271. return false;
  49272. },
  49273. enumerable: true,
  49274. configurable: true
  49275. });
  49276. // Methods
  49277. /**
  49278. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49279. */
  49280. Animation.prototype.toString = function (fullDetails) {
  49281. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49282. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49283. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49284. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49285. if (fullDetails) {
  49286. ret += ", Ranges: {";
  49287. var first = true;
  49288. for (var name in this._ranges) {
  49289. if (first) {
  49290. ret += ", ";
  49291. first = false;
  49292. }
  49293. ret += name;
  49294. }
  49295. ret += "}";
  49296. }
  49297. return ret;
  49298. };
  49299. /**
  49300. * Add an event to this animation.
  49301. */
  49302. Animation.prototype.addEvent = function (event) {
  49303. this._events.push(event);
  49304. };
  49305. /**
  49306. * Remove all events found at the given frame
  49307. * @param frame
  49308. */
  49309. Animation.prototype.removeEvents = function (frame) {
  49310. for (var index = 0; index < this._events.length; index++) {
  49311. if (this._events[index].frame === frame) {
  49312. this._events.splice(index, 1);
  49313. index--;
  49314. }
  49315. }
  49316. };
  49317. Animation.prototype.getEvents = function () {
  49318. return this._events;
  49319. };
  49320. Animation.prototype.createRange = function (name, from, to) {
  49321. // check name not already in use; could happen for bones after serialized
  49322. if (!this._ranges[name]) {
  49323. this._ranges[name] = new AnimationRange(name, from, to);
  49324. }
  49325. };
  49326. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49327. if (deleteFrames === void 0) { deleteFrames = true; }
  49328. var range = this._ranges[name];
  49329. if (!range) {
  49330. return;
  49331. }
  49332. if (deleteFrames) {
  49333. var from = range.from;
  49334. var to = range.to;
  49335. // this loop MUST go high to low for multiple splices to work
  49336. for (var key = this._keys.length - 1; key >= 0; key--) {
  49337. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49338. this._keys.splice(key, 1);
  49339. }
  49340. }
  49341. }
  49342. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49343. };
  49344. Animation.prototype.getRange = function (name) {
  49345. return this._ranges[name];
  49346. };
  49347. Animation.prototype.getKeys = function () {
  49348. return this._keys;
  49349. };
  49350. Animation.prototype.getHighestFrame = function () {
  49351. var ret = 0;
  49352. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49353. if (ret < this._keys[key].frame) {
  49354. ret = this._keys[key].frame;
  49355. }
  49356. }
  49357. return ret;
  49358. };
  49359. Animation.prototype.getEasingFunction = function () {
  49360. return this._easingFunction;
  49361. };
  49362. Animation.prototype.setEasingFunction = function (easingFunction) {
  49363. this._easingFunction = easingFunction;
  49364. };
  49365. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49366. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49367. };
  49368. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49369. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49370. };
  49371. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49372. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49373. };
  49374. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49375. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49376. };
  49377. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49378. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49379. };
  49380. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49381. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49382. };
  49383. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49384. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49385. };
  49386. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49387. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49388. };
  49389. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49390. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49391. };
  49392. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49393. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49394. };
  49395. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  49396. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49397. };
  49398. Animation.prototype.clone = function () {
  49399. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49400. clone.enableBlending = this.enableBlending;
  49401. clone.blendingSpeed = this.blendingSpeed;
  49402. if (this._keys) {
  49403. clone.setKeys(this._keys);
  49404. }
  49405. if (this._ranges) {
  49406. clone._ranges = {};
  49407. for (var name in this._ranges) {
  49408. var range = this._ranges[name];
  49409. if (!range) {
  49410. continue;
  49411. }
  49412. clone._ranges[name] = range.clone();
  49413. }
  49414. }
  49415. return clone;
  49416. };
  49417. Animation.prototype.setKeys = function (values) {
  49418. this._keys = values.slice(0);
  49419. };
  49420. Animation.prototype.serialize = function () {
  49421. var serializationObject = {};
  49422. serializationObject.name = this.name;
  49423. serializationObject.property = this.targetProperty;
  49424. serializationObject.framePerSecond = this.framePerSecond;
  49425. serializationObject.dataType = this.dataType;
  49426. serializationObject.loopBehavior = this.loopMode;
  49427. serializationObject.enableBlending = this.enableBlending;
  49428. serializationObject.blendingSpeed = this.blendingSpeed;
  49429. var dataType = this.dataType;
  49430. serializationObject.keys = [];
  49431. var keys = this.getKeys();
  49432. for (var index = 0; index < keys.length; index++) {
  49433. var animationKey = keys[index];
  49434. var key = {};
  49435. key.frame = animationKey.frame;
  49436. switch (dataType) {
  49437. case Animation.ANIMATIONTYPE_FLOAT:
  49438. key.values = [animationKey.value];
  49439. break;
  49440. case Animation.ANIMATIONTYPE_QUATERNION:
  49441. case Animation.ANIMATIONTYPE_MATRIX:
  49442. case Animation.ANIMATIONTYPE_VECTOR3:
  49443. case Animation.ANIMATIONTYPE_COLOR3:
  49444. key.values = animationKey.value.asArray();
  49445. break;
  49446. }
  49447. serializationObject.keys.push(key);
  49448. }
  49449. serializationObject.ranges = [];
  49450. for (var name in this._ranges) {
  49451. var source = this._ranges[name];
  49452. if (!source) {
  49453. continue;
  49454. }
  49455. var range = {};
  49456. range.name = name;
  49457. range.from = source.from;
  49458. range.to = source.to;
  49459. serializationObject.ranges.push(range);
  49460. }
  49461. return serializationObject;
  49462. };
  49463. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49464. get: function () {
  49465. return Animation._ANIMATIONTYPE_FLOAT;
  49466. },
  49467. enumerable: true,
  49468. configurable: true
  49469. });
  49470. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49471. get: function () {
  49472. return Animation._ANIMATIONTYPE_VECTOR3;
  49473. },
  49474. enumerable: true,
  49475. configurable: true
  49476. });
  49477. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49478. get: function () {
  49479. return Animation._ANIMATIONTYPE_VECTOR2;
  49480. },
  49481. enumerable: true,
  49482. configurable: true
  49483. });
  49484. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49485. get: function () {
  49486. return Animation._ANIMATIONTYPE_SIZE;
  49487. },
  49488. enumerable: true,
  49489. configurable: true
  49490. });
  49491. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49492. get: function () {
  49493. return Animation._ANIMATIONTYPE_QUATERNION;
  49494. },
  49495. enumerable: true,
  49496. configurable: true
  49497. });
  49498. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49499. get: function () {
  49500. return Animation._ANIMATIONTYPE_MATRIX;
  49501. },
  49502. enumerable: true,
  49503. configurable: true
  49504. });
  49505. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49506. get: function () {
  49507. return Animation._ANIMATIONTYPE_COLOR3;
  49508. },
  49509. enumerable: true,
  49510. configurable: true
  49511. });
  49512. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49513. get: function () {
  49514. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49515. },
  49516. enumerable: true,
  49517. configurable: true
  49518. });
  49519. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49520. get: function () {
  49521. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49522. },
  49523. enumerable: true,
  49524. configurable: true
  49525. });
  49526. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49527. get: function () {
  49528. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49529. },
  49530. enumerable: true,
  49531. configurable: true
  49532. });
  49533. Animation.Parse = function (parsedAnimation) {
  49534. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49535. var dataType = parsedAnimation.dataType;
  49536. var keys = [];
  49537. var data;
  49538. var index;
  49539. if (parsedAnimation.enableBlending) {
  49540. animation.enableBlending = parsedAnimation.enableBlending;
  49541. }
  49542. if (parsedAnimation.blendingSpeed) {
  49543. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49544. }
  49545. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49546. var key = parsedAnimation.keys[index];
  49547. var inTangent;
  49548. var outTangent;
  49549. switch (dataType) {
  49550. case Animation.ANIMATIONTYPE_FLOAT:
  49551. data = key.values[0];
  49552. if (key.values.length >= 1) {
  49553. inTangent = key.values[1];
  49554. }
  49555. if (key.values.length >= 2) {
  49556. outTangent = key.values[2];
  49557. }
  49558. break;
  49559. case Animation.ANIMATIONTYPE_QUATERNION:
  49560. data = BABYLON.Quaternion.FromArray(key.values);
  49561. if (key.values.length >= 8) {
  49562. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49563. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49564. inTangent = _inTangent;
  49565. }
  49566. }
  49567. if (key.values.length >= 12) {
  49568. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49569. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49570. outTangent = _outTangent;
  49571. }
  49572. }
  49573. break;
  49574. case Animation.ANIMATIONTYPE_MATRIX:
  49575. data = BABYLON.Matrix.FromArray(key.values);
  49576. break;
  49577. case Animation.ANIMATIONTYPE_COLOR3:
  49578. data = BABYLON.Color3.FromArray(key.values);
  49579. break;
  49580. case Animation.ANIMATIONTYPE_VECTOR3:
  49581. default:
  49582. data = BABYLON.Vector3.FromArray(key.values);
  49583. break;
  49584. }
  49585. var keyData = {};
  49586. keyData.frame = key.frame;
  49587. keyData.value = data;
  49588. if (inTangent != undefined) {
  49589. keyData.inTangent = inTangent;
  49590. }
  49591. if (outTangent != undefined) {
  49592. keyData.outTangent = outTangent;
  49593. }
  49594. keys.push(keyData);
  49595. }
  49596. animation.setKeys(keys);
  49597. if (parsedAnimation.ranges) {
  49598. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49599. data = parsedAnimation.ranges[index];
  49600. animation.createRange(data.name, data.from, data.to);
  49601. }
  49602. }
  49603. return animation;
  49604. };
  49605. Animation.AppendSerializedAnimations = function (source, destination) {
  49606. if (source.animations) {
  49607. destination.animations = [];
  49608. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49609. var animation = source.animations[animationIndex];
  49610. destination.animations.push(animation.serialize());
  49611. }
  49612. }
  49613. };
  49614. Animation.AllowMatricesInterpolation = false;
  49615. // Statics
  49616. Animation._ANIMATIONTYPE_FLOAT = 0;
  49617. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49618. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49619. Animation._ANIMATIONTYPE_MATRIX = 3;
  49620. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49621. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49622. Animation._ANIMATIONTYPE_SIZE = 6;
  49623. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49624. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49625. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49626. return Animation;
  49627. }());
  49628. BABYLON.Animation = Animation;
  49629. })(BABYLON || (BABYLON = {}));
  49630. //# sourceMappingURL=babylon.animation.js.map
  49631. "use strict";
  49632. var BABYLON;
  49633. (function (BABYLON) {
  49634. /**
  49635. * This class defines the direct association between an animation and a target
  49636. */
  49637. var TargetedAnimation = /** @class */ (function () {
  49638. function TargetedAnimation() {
  49639. }
  49640. return TargetedAnimation;
  49641. }());
  49642. BABYLON.TargetedAnimation = TargetedAnimation;
  49643. /**
  49644. * Use this class to create coordinated animations on multiple targets
  49645. */
  49646. var AnimationGroup = /** @class */ (function () {
  49647. function AnimationGroup(name, scene) {
  49648. if (scene === void 0) { scene = null; }
  49649. this.name = name;
  49650. this._targetedAnimations = new Array();
  49651. this._animatables = new Array();
  49652. this._from = Number.MAX_VALUE;
  49653. this._to = -Number.MAX_VALUE;
  49654. this._speedRatio = 1;
  49655. this.onAnimationEndObservable = new BABYLON.Observable();
  49656. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49657. this._scene.animationGroups.push(this);
  49658. }
  49659. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49660. /**
  49661. * Define if the animations are started
  49662. */
  49663. get: function () {
  49664. return this._isStarted;
  49665. },
  49666. enumerable: true,
  49667. configurable: true
  49668. });
  49669. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49670. /**
  49671. * Gets or sets the speed ratio to use for all animations
  49672. */
  49673. get: function () {
  49674. return this._speedRatio;
  49675. },
  49676. /**
  49677. * Gets or sets the speed ratio to use for all animations
  49678. */
  49679. set: function (value) {
  49680. if (this._speedRatio === value) {
  49681. return;
  49682. }
  49683. this._speedRatio = value;
  49684. for (var index = 0; index < this._animatables.length; index++) {
  49685. var animatable = this._animatables[index];
  49686. animatable.speedRatio = this._speedRatio;
  49687. }
  49688. },
  49689. enumerable: true,
  49690. configurable: true
  49691. });
  49692. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49693. /**
  49694. * Gets the targeted animations for this animation group
  49695. */
  49696. get: function () {
  49697. return this._targetedAnimations;
  49698. },
  49699. enumerable: true,
  49700. configurable: true
  49701. });
  49702. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  49703. /**
  49704. * returning the list of animatables controlled by this animation group.
  49705. */
  49706. get: function () {
  49707. return this._animatables;
  49708. },
  49709. enumerable: true,
  49710. configurable: true
  49711. });
  49712. /**
  49713. * Add an animation (with its target) in the group
  49714. * @param animation defines the animation we want to add
  49715. * @param target defines the target of the animation
  49716. * @returns the {BABYLON.TargetedAnimation} object
  49717. */
  49718. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  49719. var targetedAnimation = {
  49720. animation: animation,
  49721. target: target
  49722. };
  49723. var keys = animation.getKeys();
  49724. if (this._from > keys[0].frame) {
  49725. this._from = keys[0].frame;
  49726. }
  49727. if (this._to < keys[keys.length - 1].frame) {
  49728. this._to = keys[keys.length - 1].frame;
  49729. }
  49730. this._targetedAnimations.push(targetedAnimation);
  49731. return targetedAnimation;
  49732. };
  49733. /**
  49734. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  49735. * It can add constant keys at begin or end
  49736. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  49737. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  49738. */
  49739. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  49740. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  49741. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  49742. beginFrame = Math.max(beginFrame, this._from);
  49743. endFrame = Math.min(endFrame, this._to);
  49744. for (var index = 0; index < this._targetedAnimations.length; index++) {
  49745. var targetedAnimation = this._targetedAnimations[index];
  49746. var keys = targetedAnimation.animation.getKeys();
  49747. var startKey = keys[0];
  49748. var endKey = keys[keys.length - 1];
  49749. if (startKey.frame > beginFrame) {
  49750. var newKey = {
  49751. frame: beginFrame,
  49752. value: startKey.value,
  49753. inTangent: startKey.inTangent,
  49754. outTangent: startKey.outTangent,
  49755. interpolation: startKey.interpolation
  49756. };
  49757. keys.splice(0, 0, newKey);
  49758. }
  49759. if (endKey.frame < endFrame) {
  49760. var newKey = {
  49761. frame: endFrame,
  49762. value: endKey.value,
  49763. inTangent: endKey.outTangent,
  49764. outTangent: endKey.outTangent,
  49765. interpolation: endKey.interpolation
  49766. };
  49767. keys.push(newKey);
  49768. }
  49769. }
  49770. return this;
  49771. };
  49772. /**
  49773. * Start all animations on given targets
  49774. * @param loop defines if animations must loop
  49775. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  49776. * @param from defines the from key (optional)
  49777. * @param to defines the to key (optional)
  49778. * @returns the current animation group
  49779. */
  49780. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  49781. var _this = this;
  49782. if (loop === void 0) { loop = false; }
  49783. if (speedRatio === void 0) { speedRatio = 1; }
  49784. if (this._isStarted || this._targetedAnimations.length === 0) {
  49785. return this;
  49786. }
  49787. var _loop_1 = function () {
  49788. var targetedAnimation = this_1._targetedAnimations[index];
  49789. if (!targetedAnimation.target.animations) {
  49790. targetedAnimation.target.animations = [];
  49791. }
  49792. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  49793. targetedAnimation.target.animations.push(targetedAnimation.animation);
  49794. }
  49795. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  49796. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  49797. }));
  49798. };
  49799. var this_1 = this;
  49800. for (var index = 0; index < this._targetedAnimations.length; index++) {
  49801. _loop_1();
  49802. }
  49803. this._speedRatio = speedRatio;
  49804. this._isStarted = true;
  49805. return this;
  49806. };
  49807. /**
  49808. * Pause all animations
  49809. */
  49810. AnimationGroup.prototype.pause = function () {
  49811. if (!this._isStarted) {
  49812. return this;
  49813. }
  49814. for (var index = 0; index < this._animatables.length; index++) {
  49815. var animatable = this._animatables[index];
  49816. animatable.pause();
  49817. }
  49818. return this;
  49819. };
  49820. /**
  49821. * Play all animations to initial state
  49822. * This function will start() the animations if they were not started or will restart() them if they were paused
  49823. * @param loop defines if animations must loop
  49824. */
  49825. AnimationGroup.prototype.play = function (loop) {
  49826. if (this.isStarted) {
  49827. if (loop !== undefined) {
  49828. for (var index = 0; index < this._animatables.length; index++) {
  49829. var animatable = this._animatables[index];
  49830. animatable.loopAnimation = loop;
  49831. }
  49832. }
  49833. this.restart();
  49834. }
  49835. else {
  49836. this.start(loop, this._speedRatio);
  49837. }
  49838. return this;
  49839. };
  49840. /**
  49841. * Reset all animations to initial state
  49842. */
  49843. AnimationGroup.prototype.reset = function () {
  49844. if (!this._isStarted) {
  49845. return this;
  49846. }
  49847. for (var index = 0; index < this._animatables.length; index++) {
  49848. var animatable = this._animatables[index];
  49849. animatable.reset();
  49850. }
  49851. return this;
  49852. };
  49853. /**
  49854. * Restart animations from key 0
  49855. */
  49856. AnimationGroup.prototype.restart = function () {
  49857. if (!this._isStarted) {
  49858. return this;
  49859. }
  49860. for (var index = 0; index < this._animatables.length; index++) {
  49861. var animatable = this._animatables[index];
  49862. animatable.restart();
  49863. }
  49864. return this;
  49865. };
  49866. /**
  49867. * Stop all animations
  49868. */
  49869. AnimationGroup.prototype.stop = function () {
  49870. if (!this._isStarted) {
  49871. return this;
  49872. }
  49873. for (var index = 0; index < this._animatables.length; index++) {
  49874. var animatable = this._animatables[index];
  49875. animatable.stop();
  49876. }
  49877. this._isStarted = false;
  49878. return this;
  49879. };
  49880. /**
  49881. * Goes to a specific frame in this animation group
  49882. *
  49883. * @param frame the frame number to go to
  49884. * @return the animationGroup
  49885. */
  49886. AnimationGroup.prototype.goToFrame = function (frame) {
  49887. if (!this._isStarted) {
  49888. return this;
  49889. }
  49890. for (var index = 0; index < this._animatables.length; index++) {
  49891. var animatable = this._animatables[index];
  49892. animatable.goToFrame(frame);
  49893. }
  49894. return this;
  49895. };
  49896. /**
  49897. * Dispose all associated resources
  49898. */
  49899. AnimationGroup.prototype.dispose = function () {
  49900. this._targetedAnimations = [];
  49901. this._animatables = [];
  49902. var index = this._scene.animationGroups.indexOf(this);
  49903. if (index > -1) {
  49904. this._scene.animationGroups.splice(index, 1);
  49905. }
  49906. };
  49907. return AnimationGroup;
  49908. }());
  49909. BABYLON.AnimationGroup = AnimationGroup;
  49910. })(BABYLON || (BABYLON = {}));
  49911. //# sourceMappingURL=babylon.animationGroup.js.map
  49912. "use strict";
  49913. var BABYLON;
  49914. (function (BABYLON) {
  49915. var RuntimeAnimation = /** @class */ (function () {
  49916. /**
  49917. * Create a new RuntimeAnimation object
  49918. * @param target defines the target of the animation
  49919. * @param animation defines the source {BABYLON.Animation} object
  49920. * @param scene defines the hosting scene
  49921. * @param host defines the initiating Animatable
  49922. */
  49923. function RuntimeAnimation(target, animation, scene, host) {
  49924. this._currentFrame = 0;
  49925. this._offsetsCache = {};
  49926. this._highLimitsCache = {};
  49927. this._stopped = false;
  49928. this._blendingFactor = 0;
  49929. this._targetPath = "";
  49930. this._weight = 1.0;
  49931. this._ratioOffset = 0;
  49932. this._previousDelay = 0;
  49933. this._previousRatio = 0;
  49934. this._animation = animation;
  49935. this._target = target;
  49936. this._scene = scene;
  49937. this._host = host;
  49938. animation._runtimeAnimations.push(this);
  49939. }
  49940. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  49941. /**
  49942. * Gets the current frame
  49943. */
  49944. get: function () {
  49945. return this._currentFrame;
  49946. },
  49947. enumerable: true,
  49948. configurable: true
  49949. });
  49950. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  49951. /**
  49952. * Gets the weight of the runtime animation
  49953. */
  49954. get: function () {
  49955. return this._weight;
  49956. },
  49957. enumerable: true,
  49958. configurable: true
  49959. });
  49960. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  49961. /**
  49962. * Gets the original value of the runtime animation
  49963. */
  49964. get: function () {
  49965. return this._originalValue;
  49966. },
  49967. enumerable: true,
  49968. configurable: true
  49969. });
  49970. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  49971. /**
  49972. * Gets the current value of the runtime animation
  49973. */
  49974. get: function () {
  49975. return this._currentValue;
  49976. },
  49977. enumerable: true,
  49978. configurable: true
  49979. });
  49980. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  49981. /**
  49982. * Gets the path where to store the animated value in the target
  49983. */
  49984. get: function () {
  49985. return this._targetPath;
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  49991. /**
  49992. * Gets the actual target of the runtime animation
  49993. */
  49994. get: function () {
  49995. return this._activeTarget;
  49996. },
  49997. enumerable: true,
  49998. configurable: true
  49999. });
  50000. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50001. get: function () {
  50002. return this._animation;
  50003. },
  50004. enumerable: true,
  50005. configurable: true
  50006. });
  50007. RuntimeAnimation.prototype.reset = function () {
  50008. this._offsetsCache = {};
  50009. this._highLimitsCache = {};
  50010. this._currentFrame = 0;
  50011. this._blendingFactor = 0;
  50012. this._originalValue = null;
  50013. };
  50014. RuntimeAnimation.prototype.isStopped = function () {
  50015. return this._stopped;
  50016. };
  50017. RuntimeAnimation.prototype.dispose = function () {
  50018. var index = this._animation.runtimeAnimations.indexOf(this);
  50019. if (index > -1) {
  50020. this._animation.runtimeAnimations.splice(index, 1);
  50021. }
  50022. };
  50023. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50024. if (typeof value === "function") {
  50025. return value();
  50026. }
  50027. return value;
  50028. };
  50029. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50030. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50031. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50032. }
  50033. this._currentFrame = currentFrame;
  50034. var keys = this._animation.getKeys();
  50035. // Try to get a hash to find the right key
  50036. 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));
  50037. if (keys[startKeyIndex].frame >= currentFrame) {
  50038. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50039. startKeyIndex--;
  50040. }
  50041. }
  50042. for (var key = startKeyIndex; key < keys.length; key++) {
  50043. var endKey = keys[key + 1];
  50044. if (endKey.frame >= currentFrame) {
  50045. var startKey = keys[key];
  50046. var startValue = this._getKeyValue(startKey.value);
  50047. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50048. return startValue;
  50049. }
  50050. var endValue = this._getKeyValue(endKey.value);
  50051. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50052. var frameDelta = endKey.frame - startKey.frame;
  50053. // gradient : percent of currentFrame between the frame inf and the frame sup
  50054. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50055. // check for easingFunction and correction of gradient
  50056. var easingFunction = this._animation.getEasingFunction();
  50057. if (easingFunction != null) {
  50058. gradient = easingFunction.ease(gradient);
  50059. }
  50060. switch (this._animation.dataType) {
  50061. // Float
  50062. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50063. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50064. switch (loopMode) {
  50065. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50066. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50067. return floatValue;
  50068. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50069. return offsetValue * repeatCount + floatValue;
  50070. }
  50071. break;
  50072. // Quaternion
  50073. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50074. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50075. switch (loopMode) {
  50076. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50077. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50078. return quatValue;
  50079. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50080. return quatValue.add(offsetValue.scale(repeatCount));
  50081. }
  50082. return quatValue;
  50083. // Vector3
  50084. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50085. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50086. switch (loopMode) {
  50087. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50088. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50089. return vec3Value;
  50090. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50091. return vec3Value.add(offsetValue.scale(repeatCount));
  50092. }
  50093. // Vector2
  50094. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50095. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50096. switch (loopMode) {
  50097. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50098. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50099. return vec2Value;
  50100. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50101. return vec2Value.add(offsetValue.scale(repeatCount));
  50102. }
  50103. // Size
  50104. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50105. switch (loopMode) {
  50106. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50107. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50108. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50109. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50110. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50111. }
  50112. // Color3
  50113. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50114. switch (loopMode) {
  50115. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50116. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50117. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50118. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50119. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50120. }
  50121. // Matrix
  50122. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50123. switch (loopMode) {
  50124. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50125. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50126. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50127. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  50128. }
  50129. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50130. return startValue;
  50131. }
  50132. default:
  50133. break;
  50134. }
  50135. break;
  50136. }
  50137. }
  50138. return this._getKeyValue(keys[keys.length - 1].value);
  50139. };
  50140. /**
  50141. * Affect the interpolated value to the target
  50142. * @param currentValue defines the value computed by the animation
  50143. * @param weight defines the weight to apply to this value
  50144. */
  50145. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50146. if (weight === void 0) { weight = 1.0; }
  50147. // Set value
  50148. var path;
  50149. var destination;
  50150. var targetPropertyPath = this._animation.targetPropertyPath;
  50151. if (targetPropertyPath.length > 1) {
  50152. var property = this._target[targetPropertyPath[0]];
  50153. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50154. property = property[targetPropertyPath[index]];
  50155. }
  50156. path = targetPropertyPath[targetPropertyPath.length - 1];
  50157. destination = property;
  50158. }
  50159. else {
  50160. path = targetPropertyPath[0];
  50161. destination = this._target;
  50162. }
  50163. this._targetPath = path;
  50164. this._activeTarget = destination;
  50165. this._weight = weight;
  50166. // Blending
  50167. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50168. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50169. if (enableBlending && this._blendingFactor <= 1.0) {
  50170. if (!this._originalBlendValue) {
  50171. var originalValue = destination[path];
  50172. if (originalValue.clone) {
  50173. this._originalBlendValue = originalValue.clone();
  50174. }
  50175. else {
  50176. this._originalBlendValue = originalValue;
  50177. }
  50178. }
  50179. }
  50180. if (weight !== -1.0) {
  50181. if (!this._originalValue) {
  50182. var originalValue = void 0;
  50183. if (destination.getRestPose) {
  50184. originalValue = destination.getRestPose();
  50185. }
  50186. else {
  50187. originalValue = destination[path];
  50188. }
  50189. if (originalValue.clone) {
  50190. this._originalValue = originalValue.clone();
  50191. }
  50192. else {
  50193. this._originalValue = originalValue;
  50194. }
  50195. }
  50196. }
  50197. if (enableBlending && this._blendingFactor <= 1.0) {
  50198. if (this._originalBlendValue.prototype) {
  50199. if (this._originalBlendValue.prototype.Lerp) {
  50200. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50201. }
  50202. else {
  50203. this._currentValue = currentValue;
  50204. }
  50205. }
  50206. else if (this._originalBlendValue.m) {
  50207. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50208. }
  50209. else {
  50210. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50211. }
  50212. this._blendingFactor += blendingSpeed;
  50213. }
  50214. else {
  50215. this._currentValue = currentValue;
  50216. }
  50217. if (weight !== -1.0) {
  50218. this._scene._registerTargetForLateAnimationBinding(this);
  50219. }
  50220. else {
  50221. destination[path] = this._currentValue;
  50222. }
  50223. if (this._target.markAsDirty) {
  50224. this._target.markAsDirty(this._animation.targetProperty);
  50225. }
  50226. };
  50227. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50228. if (this._target && this._target.animationPropertiesOverride) {
  50229. return this._target.animationPropertiesOverride.loopMode;
  50230. }
  50231. return this._animation.loopMode;
  50232. };
  50233. /**
  50234. * Move the current animation to a given frame
  50235. * @param frame defines the frame to move to
  50236. */
  50237. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50238. var keys = this._animation.getKeys();
  50239. if (frame < keys[0].frame) {
  50240. frame = keys[0].frame;
  50241. }
  50242. else if (frame > keys[keys.length - 1].frame) {
  50243. frame = keys[keys.length - 1].frame;
  50244. }
  50245. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50246. this.setValue(currentValue, -1);
  50247. };
  50248. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50249. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50250. this._ratioOffset = this._previousRatio - newRatio;
  50251. };
  50252. /**
  50253. * Execute the current animation
  50254. * @param delay defines the delay to add to the current frame
  50255. * @param from defines the lower bound of the animation range
  50256. * @param to defines the upper bound of the animation range
  50257. * @param loop defines if the current animation must loop
  50258. * @param speedRatio defines the current speed ratio
  50259. * @param weight defines the weight of the animation (default is -1 so no weight)
  50260. * @returns a boolean indicating if the animation has ended
  50261. */
  50262. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50263. if (weight === void 0) { weight = -1.0; }
  50264. var targetPropertyPath = this._animation.targetPropertyPath;
  50265. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50266. this._stopped = true;
  50267. return false;
  50268. }
  50269. var returnValue = true;
  50270. var keys = this._animation.getKeys();
  50271. // Adding a start key at frame 0 if missing
  50272. if (keys[0].frame !== 0) {
  50273. var newKey = { frame: 0, value: keys[0].value };
  50274. keys.splice(0, 0, newKey);
  50275. }
  50276. // Check limits
  50277. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50278. from = keys[0].frame;
  50279. }
  50280. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50281. to = keys[keys.length - 1].frame;
  50282. }
  50283. //to and from cannot be the same key
  50284. if (from === to) {
  50285. if (from > keys[0].frame) {
  50286. from--;
  50287. }
  50288. else if (to < keys[keys.length - 1].frame) {
  50289. to++;
  50290. }
  50291. }
  50292. // Compute ratio
  50293. var range = to - from;
  50294. var offsetValue;
  50295. // ratio represents the frame delta between from and to
  50296. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50297. var highLimitValue = 0;
  50298. this._previousDelay = delay;
  50299. this._previousRatio = ratio;
  50300. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50301. returnValue = false;
  50302. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50303. }
  50304. else {
  50305. // Get max value if required
  50306. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50307. var keyOffset = to.toString() + from.toString();
  50308. if (!this._offsetsCache[keyOffset]) {
  50309. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50310. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50311. switch (this._animation.dataType) {
  50312. // Float
  50313. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50314. this._offsetsCache[keyOffset] = toValue - fromValue;
  50315. break;
  50316. // Quaternion
  50317. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50318. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50319. break;
  50320. // Vector3
  50321. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50322. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50323. // Vector2
  50324. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50325. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50326. // Size
  50327. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50328. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50329. // Color3
  50330. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50331. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50332. default:
  50333. break;
  50334. }
  50335. this._highLimitsCache[keyOffset] = toValue;
  50336. }
  50337. highLimitValue = this._highLimitsCache[keyOffset];
  50338. offsetValue = this._offsetsCache[keyOffset];
  50339. }
  50340. }
  50341. if (offsetValue === undefined) {
  50342. switch (this._animation.dataType) {
  50343. // Float
  50344. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50345. offsetValue = 0;
  50346. break;
  50347. // Quaternion
  50348. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50349. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50350. break;
  50351. // Vector3
  50352. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50353. offsetValue = BABYLON.Vector3.Zero();
  50354. break;
  50355. // Vector2
  50356. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50357. offsetValue = BABYLON.Vector2.Zero();
  50358. break;
  50359. // Size
  50360. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50361. offsetValue = BABYLON.Size.Zero();
  50362. break;
  50363. // Color3
  50364. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50365. offsetValue = BABYLON.Color3.Black();
  50366. }
  50367. }
  50368. // Compute value
  50369. var repeatCount = (ratio / range) >> 0;
  50370. var currentFrame = returnValue ? from + ratio % range : to;
  50371. // Need to normalize?
  50372. if (this._host && this._host.syncRoot) {
  50373. var syncRoot = this._host.syncRoot;
  50374. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50375. currentFrame = from + (to - from) * hostNormalizedFrame;
  50376. }
  50377. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50378. // Set value
  50379. this.setValue(currentValue, weight);
  50380. // Check events
  50381. var events = this._animation.getEvents();
  50382. for (var index = 0; index < events.length; index++) {
  50383. // Make sure current frame has passed event frame and that event frame is within the current range
  50384. // Also, handle both forward and reverse animations
  50385. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50386. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50387. var event = events[index];
  50388. if (!event.isDone) {
  50389. // If event should be done only once, remove it.
  50390. if (event.onlyOnce) {
  50391. events.splice(index, 1);
  50392. index--;
  50393. }
  50394. event.isDone = true;
  50395. event.action();
  50396. } // Don't do anything if the event has already be done.
  50397. }
  50398. else if (events[index].isDone && !events[index].onlyOnce) {
  50399. // reset event, the animation is looping
  50400. events[index].isDone = false;
  50401. }
  50402. }
  50403. if (!returnValue) {
  50404. this._stopped = true;
  50405. }
  50406. return returnValue;
  50407. };
  50408. return RuntimeAnimation;
  50409. }());
  50410. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50411. })(BABYLON || (BABYLON = {}));
  50412. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50413. "use strict";
  50414. var BABYLON;
  50415. (function (BABYLON) {
  50416. var Animatable = /** @class */ (function () {
  50417. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  50418. if (fromFrame === void 0) { fromFrame = 0; }
  50419. if (toFrame === void 0) { toFrame = 100; }
  50420. if (loopAnimation === void 0) { loopAnimation = false; }
  50421. if (speedRatio === void 0) { speedRatio = 1.0; }
  50422. this.target = target;
  50423. this.fromFrame = fromFrame;
  50424. this.toFrame = toFrame;
  50425. this.loopAnimation = loopAnimation;
  50426. this.onAnimationEnd = onAnimationEnd;
  50427. this._localDelayOffset = null;
  50428. this._pausedDelay = null;
  50429. this._runtimeAnimations = new Array();
  50430. this._paused = false;
  50431. this._speedRatio = 1;
  50432. this._weight = -1.0;
  50433. this.animationStarted = false;
  50434. if (animations) {
  50435. this.appendAnimations(target, animations);
  50436. }
  50437. this._speedRatio = speedRatio;
  50438. this._scene = scene;
  50439. scene._activeAnimatables.push(this);
  50440. }
  50441. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50442. /**
  50443. * Gets the root Animatable used to synchronize and normalize animations
  50444. */
  50445. get: function () {
  50446. return this._syncRoot;
  50447. },
  50448. enumerable: true,
  50449. configurable: true
  50450. });
  50451. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50452. /**
  50453. * Gets the current frame of the first RuntimeAnimation
  50454. * Used to synchronize Animatables
  50455. */
  50456. get: function () {
  50457. if (this._runtimeAnimations.length === 0) {
  50458. return 0;
  50459. }
  50460. return this._runtimeAnimations[0].currentFrame;
  50461. },
  50462. enumerable: true,
  50463. configurable: true
  50464. });
  50465. Object.defineProperty(Animatable.prototype, "weight", {
  50466. /**
  50467. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50468. */
  50469. get: function () {
  50470. return this._weight;
  50471. },
  50472. set: function (value) {
  50473. if (value === -1) {
  50474. this._weight = -1;
  50475. return;
  50476. }
  50477. // Else weight must be in [0, 1] range
  50478. this._weight = Math.min(Math.max(value, 0), 1.0);
  50479. },
  50480. enumerable: true,
  50481. configurable: true
  50482. });
  50483. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50484. /**
  50485. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50486. */
  50487. get: function () {
  50488. return this._speedRatio;
  50489. },
  50490. set: function (value) {
  50491. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50492. var animation = this._runtimeAnimations[index];
  50493. animation._prepareForSpeedRatioChange(value);
  50494. }
  50495. this._speedRatio = value;
  50496. },
  50497. enumerable: true,
  50498. configurable: true
  50499. });
  50500. // Methods
  50501. /**
  50502. * Synchronize and normalize current Animatable with a source Animatable.
  50503. * This is useful when using animation weights and when animations are not of the same length
  50504. * @param root defines the root Animatable to synchronize with
  50505. * @returns the current Animatable
  50506. */
  50507. Animatable.prototype.syncWith = function (root) {
  50508. this._syncRoot = root;
  50509. if (root) {
  50510. // Make sure this animatable will animate after the root
  50511. var index = this._scene._activeAnimatables.indexOf(this);
  50512. if (index > -1) {
  50513. this._scene._activeAnimatables.splice(index, 1);
  50514. this._scene._activeAnimatables.push(this);
  50515. }
  50516. }
  50517. return this;
  50518. };
  50519. Animatable.prototype.getAnimations = function () {
  50520. return this._runtimeAnimations;
  50521. };
  50522. Animatable.prototype.appendAnimations = function (target, animations) {
  50523. for (var index = 0; index < animations.length; index++) {
  50524. var animation = animations[index];
  50525. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50526. }
  50527. };
  50528. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50529. var runtimeAnimations = this._runtimeAnimations;
  50530. for (var index = 0; index < runtimeAnimations.length; index++) {
  50531. if (runtimeAnimations[index].animation.targetProperty === property) {
  50532. return runtimeAnimations[index].animation;
  50533. }
  50534. }
  50535. return null;
  50536. };
  50537. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50538. var runtimeAnimations = this._runtimeAnimations;
  50539. for (var index = 0; index < runtimeAnimations.length; index++) {
  50540. if (runtimeAnimations[index].animation.targetProperty === property) {
  50541. return runtimeAnimations[index];
  50542. }
  50543. }
  50544. return null;
  50545. };
  50546. Animatable.prototype.reset = function () {
  50547. var runtimeAnimations = this._runtimeAnimations;
  50548. for (var index = 0; index < runtimeAnimations.length; index++) {
  50549. runtimeAnimations[index].reset();
  50550. }
  50551. // Reset to original value
  50552. for (index = 0; index < runtimeAnimations.length; index++) {
  50553. var animation = runtimeAnimations[index];
  50554. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  50555. }
  50556. this._localDelayOffset = null;
  50557. this._pausedDelay = null;
  50558. };
  50559. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50560. var runtimeAnimations = this._runtimeAnimations;
  50561. for (var index = 0; index < runtimeAnimations.length; index++) {
  50562. runtimeAnimations[index].animation.enableBlending = true;
  50563. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50564. }
  50565. };
  50566. Animatable.prototype.disableBlending = function () {
  50567. var runtimeAnimations = this._runtimeAnimations;
  50568. for (var index = 0; index < runtimeAnimations.length; index++) {
  50569. runtimeAnimations[index].animation.enableBlending = false;
  50570. }
  50571. };
  50572. Animatable.prototype.goToFrame = function (frame) {
  50573. var runtimeAnimations = this._runtimeAnimations;
  50574. if (runtimeAnimations[0]) {
  50575. var fps = runtimeAnimations[0].animation.framePerSecond;
  50576. var currentFrame = runtimeAnimations[0].currentFrame;
  50577. var adjustTime = frame - currentFrame;
  50578. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50579. if (this._localDelayOffset === null) {
  50580. this._localDelayOffset = 0;
  50581. }
  50582. this._localDelayOffset -= delay;
  50583. }
  50584. for (var index = 0; index < runtimeAnimations.length; index++) {
  50585. runtimeAnimations[index].goToFrame(frame);
  50586. }
  50587. };
  50588. Animatable.prototype.pause = function () {
  50589. if (this._paused) {
  50590. return;
  50591. }
  50592. this._paused = true;
  50593. };
  50594. Animatable.prototype.restart = function () {
  50595. this._paused = false;
  50596. };
  50597. Animatable.prototype.stop = function (animationName) {
  50598. if (animationName) {
  50599. var idx = this._scene._activeAnimatables.indexOf(this);
  50600. if (idx > -1) {
  50601. var runtimeAnimations = this._runtimeAnimations;
  50602. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  50603. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  50604. continue;
  50605. }
  50606. runtimeAnimations[index].dispose();
  50607. runtimeAnimations.splice(index, 1);
  50608. }
  50609. if (runtimeAnimations.length == 0) {
  50610. this._scene._activeAnimatables.splice(idx, 1);
  50611. if (this.onAnimationEnd) {
  50612. this.onAnimationEnd();
  50613. }
  50614. }
  50615. }
  50616. }
  50617. else {
  50618. var index = this._scene._activeAnimatables.indexOf(this);
  50619. if (index > -1) {
  50620. this._scene._activeAnimatables.splice(index, 1);
  50621. var runtimeAnimations = this._runtimeAnimations;
  50622. for (var index = 0; index < runtimeAnimations.length; index++) {
  50623. runtimeAnimations[index].dispose();
  50624. }
  50625. if (this.onAnimationEnd) {
  50626. this.onAnimationEnd();
  50627. }
  50628. }
  50629. }
  50630. };
  50631. Animatable.prototype._animate = function (delay) {
  50632. if (this._paused) {
  50633. this.animationStarted = false;
  50634. if (this._pausedDelay === null) {
  50635. this._pausedDelay = delay;
  50636. }
  50637. return true;
  50638. }
  50639. if (this._localDelayOffset === null) {
  50640. this._localDelayOffset = delay;
  50641. this._pausedDelay = null;
  50642. }
  50643. else if (this._pausedDelay !== null) {
  50644. this._localDelayOffset += delay - this._pausedDelay;
  50645. this._pausedDelay = null;
  50646. }
  50647. if (this._weight === 0) {
  50648. return true;
  50649. }
  50650. // Animating
  50651. var running = false;
  50652. var runtimeAnimations = this._runtimeAnimations;
  50653. var index;
  50654. for (index = 0; index < runtimeAnimations.length; index++) {
  50655. var animation = runtimeAnimations[index];
  50656. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  50657. running = running || isRunning;
  50658. }
  50659. this.animationStarted = running;
  50660. if (!running) {
  50661. // Remove from active animatables
  50662. index = this._scene._activeAnimatables.indexOf(this);
  50663. this._scene._activeAnimatables.splice(index, 1);
  50664. // Dispose all runtime animations
  50665. for (index = 0; index < runtimeAnimations.length; index++) {
  50666. runtimeAnimations[index].dispose();
  50667. }
  50668. }
  50669. if (!running && this.onAnimationEnd) {
  50670. this.onAnimationEnd();
  50671. this.onAnimationEnd = null;
  50672. }
  50673. return running;
  50674. };
  50675. return Animatable;
  50676. }());
  50677. BABYLON.Animatable = Animatable;
  50678. })(BABYLON || (BABYLON = {}));
  50679. //# sourceMappingURL=babylon.animatable.js.map
  50680. "use strict";
  50681. var BABYLON;
  50682. (function (BABYLON) {
  50683. var EasingFunction = /** @class */ (function () {
  50684. function EasingFunction() {
  50685. // Properties
  50686. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  50687. }
  50688. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  50689. get: function () {
  50690. return EasingFunction._EASINGMODE_EASEIN;
  50691. },
  50692. enumerable: true,
  50693. configurable: true
  50694. });
  50695. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  50696. get: function () {
  50697. return EasingFunction._EASINGMODE_EASEOUT;
  50698. },
  50699. enumerable: true,
  50700. configurable: true
  50701. });
  50702. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  50703. get: function () {
  50704. return EasingFunction._EASINGMODE_EASEINOUT;
  50705. },
  50706. enumerable: true,
  50707. configurable: true
  50708. });
  50709. EasingFunction.prototype.setEasingMode = function (easingMode) {
  50710. var n = Math.min(Math.max(easingMode, 0), 2);
  50711. this._easingMode = n;
  50712. };
  50713. EasingFunction.prototype.getEasingMode = function () {
  50714. return this._easingMode;
  50715. };
  50716. EasingFunction.prototype.easeInCore = function (gradient) {
  50717. throw new Error('You must implement this method');
  50718. };
  50719. EasingFunction.prototype.ease = function (gradient) {
  50720. switch (this._easingMode) {
  50721. case EasingFunction.EASINGMODE_EASEIN:
  50722. return this.easeInCore(gradient);
  50723. case EasingFunction.EASINGMODE_EASEOUT:
  50724. return (1 - this.easeInCore(1 - gradient));
  50725. }
  50726. if (gradient >= 0.5) {
  50727. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  50728. }
  50729. return (this.easeInCore(gradient * 2) * 0.5);
  50730. };
  50731. //Statics
  50732. EasingFunction._EASINGMODE_EASEIN = 0;
  50733. EasingFunction._EASINGMODE_EASEOUT = 1;
  50734. EasingFunction._EASINGMODE_EASEINOUT = 2;
  50735. return EasingFunction;
  50736. }());
  50737. BABYLON.EasingFunction = EasingFunction;
  50738. var CircleEase = /** @class */ (function (_super) {
  50739. __extends(CircleEase, _super);
  50740. function CircleEase() {
  50741. return _super !== null && _super.apply(this, arguments) || this;
  50742. }
  50743. CircleEase.prototype.easeInCore = function (gradient) {
  50744. gradient = Math.max(0, Math.min(1, gradient));
  50745. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  50746. };
  50747. return CircleEase;
  50748. }(EasingFunction));
  50749. BABYLON.CircleEase = CircleEase;
  50750. var BackEase = /** @class */ (function (_super) {
  50751. __extends(BackEase, _super);
  50752. function BackEase(amplitude) {
  50753. if (amplitude === void 0) { amplitude = 1; }
  50754. var _this = _super.call(this) || this;
  50755. _this.amplitude = amplitude;
  50756. return _this;
  50757. }
  50758. BackEase.prototype.easeInCore = function (gradient) {
  50759. var num = Math.max(0, this.amplitude);
  50760. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  50761. };
  50762. return BackEase;
  50763. }(EasingFunction));
  50764. BABYLON.BackEase = BackEase;
  50765. var BounceEase = /** @class */ (function (_super) {
  50766. __extends(BounceEase, _super);
  50767. function BounceEase(bounces, bounciness) {
  50768. if (bounces === void 0) { bounces = 3; }
  50769. if (bounciness === void 0) { bounciness = 2; }
  50770. var _this = _super.call(this) || this;
  50771. _this.bounces = bounces;
  50772. _this.bounciness = bounciness;
  50773. return _this;
  50774. }
  50775. BounceEase.prototype.easeInCore = function (gradient) {
  50776. var y = Math.max(0.0, this.bounces);
  50777. var bounciness = this.bounciness;
  50778. if (bounciness <= 1.0) {
  50779. bounciness = 1.001;
  50780. }
  50781. var num9 = Math.pow(bounciness, y);
  50782. var num5 = 1.0 - bounciness;
  50783. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  50784. var num15 = gradient * num4;
  50785. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  50786. var num3 = Math.floor(num65);
  50787. var num13 = num3 + 1.0;
  50788. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  50789. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  50790. var num7 = (num8 + num12) * 0.5;
  50791. var num6 = gradient - num7;
  50792. var num2 = num7 - num8;
  50793. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  50794. };
  50795. return BounceEase;
  50796. }(EasingFunction));
  50797. BABYLON.BounceEase = BounceEase;
  50798. var CubicEase = /** @class */ (function (_super) {
  50799. __extends(CubicEase, _super);
  50800. function CubicEase() {
  50801. return _super !== null && _super.apply(this, arguments) || this;
  50802. }
  50803. CubicEase.prototype.easeInCore = function (gradient) {
  50804. return (gradient * gradient * gradient);
  50805. };
  50806. return CubicEase;
  50807. }(EasingFunction));
  50808. BABYLON.CubicEase = CubicEase;
  50809. var ElasticEase = /** @class */ (function (_super) {
  50810. __extends(ElasticEase, _super);
  50811. function ElasticEase(oscillations, springiness) {
  50812. if (oscillations === void 0) { oscillations = 3; }
  50813. if (springiness === void 0) { springiness = 3; }
  50814. var _this = _super.call(this) || this;
  50815. _this.oscillations = oscillations;
  50816. _this.springiness = springiness;
  50817. return _this;
  50818. }
  50819. ElasticEase.prototype.easeInCore = function (gradient) {
  50820. var num2;
  50821. var num3 = Math.max(0.0, this.oscillations);
  50822. var num = Math.max(0.0, this.springiness);
  50823. if (num == 0) {
  50824. num2 = gradient;
  50825. }
  50826. else {
  50827. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  50828. }
  50829. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  50830. };
  50831. return ElasticEase;
  50832. }(EasingFunction));
  50833. BABYLON.ElasticEase = ElasticEase;
  50834. var ExponentialEase = /** @class */ (function (_super) {
  50835. __extends(ExponentialEase, _super);
  50836. function ExponentialEase(exponent) {
  50837. if (exponent === void 0) { exponent = 2; }
  50838. var _this = _super.call(this) || this;
  50839. _this.exponent = exponent;
  50840. return _this;
  50841. }
  50842. ExponentialEase.prototype.easeInCore = function (gradient) {
  50843. if (this.exponent <= 0) {
  50844. return gradient;
  50845. }
  50846. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  50847. };
  50848. return ExponentialEase;
  50849. }(EasingFunction));
  50850. BABYLON.ExponentialEase = ExponentialEase;
  50851. var PowerEase = /** @class */ (function (_super) {
  50852. __extends(PowerEase, _super);
  50853. function PowerEase(power) {
  50854. if (power === void 0) { power = 2; }
  50855. var _this = _super.call(this) || this;
  50856. _this.power = power;
  50857. return _this;
  50858. }
  50859. PowerEase.prototype.easeInCore = function (gradient) {
  50860. var y = Math.max(0.0, this.power);
  50861. return Math.pow(gradient, y);
  50862. };
  50863. return PowerEase;
  50864. }(EasingFunction));
  50865. BABYLON.PowerEase = PowerEase;
  50866. var QuadraticEase = /** @class */ (function (_super) {
  50867. __extends(QuadraticEase, _super);
  50868. function QuadraticEase() {
  50869. return _super !== null && _super.apply(this, arguments) || this;
  50870. }
  50871. QuadraticEase.prototype.easeInCore = function (gradient) {
  50872. return (gradient * gradient);
  50873. };
  50874. return QuadraticEase;
  50875. }(EasingFunction));
  50876. BABYLON.QuadraticEase = QuadraticEase;
  50877. var QuarticEase = /** @class */ (function (_super) {
  50878. __extends(QuarticEase, _super);
  50879. function QuarticEase() {
  50880. return _super !== null && _super.apply(this, arguments) || this;
  50881. }
  50882. QuarticEase.prototype.easeInCore = function (gradient) {
  50883. return (gradient * gradient * gradient * gradient);
  50884. };
  50885. return QuarticEase;
  50886. }(EasingFunction));
  50887. BABYLON.QuarticEase = QuarticEase;
  50888. var QuinticEase = /** @class */ (function (_super) {
  50889. __extends(QuinticEase, _super);
  50890. function QuinticEase() {
  50891. return _super !== null && _super.apply(this, arguments) || this;
  50892. }
  50893. QuinticEase.prototype.easeInCore = function (gradient) {
  50894. return (gradient * gradient * gradient * gradient * gradient);
  50895. };
  50896. return QuinticEase;
  50897. }(EasingFunction));
  50898. BABYLON.QuinticEase = QuinticEase;
  50899. var SineEase = /** @class */ (function (_super) {
  50900. __extends(SineEase, _super);
  50901. function SineEase() {
  50902. return _super !== null && _super.apply(this, arguments) || this;
  50903. }
  50904. SineEase.prototype.easeInCore = function (gradient) {
  50905. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  50906. };
  50907. return SineEase;
  50908. }(EasingFunction));
  50909. BABYLON.SineEase = SineEase;
  50910. var BezierCurveEase = /** @class */ (function (_super) {
  50911. __extends(BezierCurveEase, _super);
  50912. function BezierCurveEase(x1, y1, x2, y2) {
  50913. if (x1 === void 0) { x1 = 0; }
  50914. if (y1 === void 0) { y1 = 0; }
  50915. if (x2 === void 0) { x2 = 1; }
  50916. if (y2 === void 0) { y2 = 1; }
  50917. var _this = _super.call(this) || this;
  50918. _this.x1 = x1;
  50919. _this.y1 = y1;
  50920. _this.x2 = x2;
  50921. _this.y2 = y2;
  50922. return _this;
  50923. }
  50924. BezierCurveEase.prototype.easeInCore = function (gradient) {
  50925. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  50926. };
  50927. return BezierCurveEase;
  50928. }(EasingFunction));
  50929. BABYLON.BezierCurveEase = BezierCurveEase;
  50930. })(BABYLON || (BABYLON = {}));
  50931. //# sourceMappingURL=babylon.easing.js.map
  50932. "use strict";
  50933. var BABYLON;
  50934. (function (BABYLON) {
  50935. /**
  50936. * A Condition applied to an Action
  50937. */
  50938. var Condition = /** @class */ (function () {
  50939. /**
  50940. * Creates a new Condition
  50941. * @param actionManager the manager of the action the condition is applied to
  50942. */
  50943. function Condition(actionManager) {
  50944. this._actionManager = actionManager;
  50945. }
  50946. /**
  50947. * Check if the current condition is valid
  50948. * @returns a boolean
  50949. */
  50950. Condition.prototype.isValid = function () {
  50951. return true;
  50952. };
  50953. /**
  50954. * Internal only
  50955. * @ignore
  50956. */
  50957. Condition.prototype._getProperty = function (propertyPath) {
  50958. return this._actionManager._getProperty(propertyPath);
  50959. };
  50960. /**
  50961. * Internal only
  50962. * @ignore
  50963. */
  50964. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  50965. return this._actionManager._getEffectiveTarget(target, propertyPath);
  50966. };
  50967. /**
  50968. * Serialize placeholder for child classes
  50969. * @returns the serialized object
  50970. */
  50971. Condition.prototype.serialize = function () {
  50972. };
  50973. /**
  50974. * Internal only
  50975. * @ignore
  50976. */
  50977. Condition.prototype._serialize = function (serializedCondition) {
  50978. return {
  50979. type: 2,
  50980. children: [],
  50981. name: serializedCondition.name,
  50982. properties: serializedCondition.properties
  50983. };
  50984. };
  50985. return Condition;
  50986. }());
  50987. BABYLON.Condition = Condition;
  50988. /**
  50989. * Defines specific conditional operators as extensions of Condition
  50990. */
  50991. var ValueCondition = /** @class */ (function (_super) {
  50992. __extends(ValueCondition, _super);
  50993. /**
  50994. * Creates a new ValueCondition
  50995. * @param actionManager manager for the action the condition applies to
  50996. * @param target for the action
  50997. * @param propertyPath path to specify the property of the target the conditional operator uses
  50998. * @param value the vale compared by the conditional operator against the current value of the property
  50999. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51000. */
  51001. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51002. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51003. var _this = _super.call(this, actionManager) || this;
  51004. _this.propertyPath = propertyPath;
  51005. _this.value = value;
  51006. _this.operator = operator;
  51007. _this._target = target;
  51008. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51009. _this._property = _this._getProperty(_this.propertyPath);
  51010. return _this;
  51011. }
  51012. Object.defineProperty(ValueCondition, "IsEqual", {
  51013. /**
  51014. * returns the number for IsEqual
  51015. */
  51016. get: function () {
  51017. return ValueCondition._IsEqual;
  51018. },
  51019. enumerable: true,
  51020. configurable: true
  51021. });
  51022. Object.defineProperty(ValueCondition, "IsDifferent", {
  51023. /**
  51024. * Returns the number for IsDifferent
  51025. */
  51026. get: function () {
  51027. return ValueCondition._IsDifferent;
  51028. },
  51029. enumerable: true,
  51030. configurable: true
  51031. });
  51032. Object.defineProperty(ValueCondition, "IsGreater", {
  51033. /**
  51034. * Returns the number for IsGreater
  51035. */
  51036. get: function () {
  51037. return ValueCondition._IsGreater;
  51038. },
  51039. enumerable: true,
  51040. configurable: true
  51041. });
  51042. Object.defineProperty(ValueCondition, "IsLesser", {
  51043. /**
  51044. * Returns the number for IsLesser
  51045. */
  51046. get: function () {
  51047. return ValueCondition._IsLesser;
  51048. },
  51049. enumerable: true,
  51050. configurable: true
  51051. });
  51052. /**
  51053. * Compares the given value with the property value for the specified conditional operator
  51054. * @returns the result of the comparison
  51055. */
  51056. ValueCondition.prototype.isValid = function () {
  51057. switch (this.operator) {
  51058. case ValueCondition.IsGreater:
  51059. return this._effectiveTarget[this._property] > this.value;
  51060. case ValueCondition.IsLesser:
  51061. return this._effectiveTarget[this._property] < this.value;
  51062. case ValueCondition.IsEqual:
  51063. case ValueCondition.IsDifferent:
  51064. var check;
  51065. if (this.value.equals) {
  51066. check = this.value.equals(this._effectiveTarget[this._property]);
  51067. }
  51068. else {
  51069. check = this.value === this._effectiveTarget[this._property];
  51070. }
  51071. return this.operator === ValueCondition.IsEqual ? check : !check;
  51072. }
  51073. return false;
  51074. };
  51075. /**
  51076. * Serialize the ValueCondition into a JSON compatible object
  51077. * @returns serialization object
  51078. */
  51079. ValueCondition.prototype.serialize = function () {
  51080. return this._serialize({
  51081. name: "ValueCondition",
  51082. properties: [
  51083. BABYLON.Action._GetTargetProperty(this._target),
  51084. { name: "propertyPath", value: this.propertyPath },
  51085. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51086. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51087. ]
  51088. });
  51089. };
  51090. /**
  51091. * Gets the name of the conditional operator for the ValueCondition
  51092. * @param operator the conditional operator
  51093. * @returns the name
  51094. */
  51095. ValueCondition.GetOperatorName = function (operator) {
  51096. switch (operator) {
  51097. case ValueCondition._IsEqual: return "IsEqual";
  51098. case ValueCondition._IsDifferent: return "IsDifferent";
  51099. case ValueCondition._IsGreater: return "IsGreater";
  51100. case ValueCondition._IsLesser: return "IsLesser";
  51101. default: return "";
  51102. }
  51103. };
  51104. /**
  51105. * Internal only
  51106. * @ignore
  51107. */
  51108. ValueCondition._IsEqual = 0;
  51109. /**
  51110. * Internal only
  51111. * @ignore
  51112. */
  51113. ValueCondition._IsDifferent = 1;
  51114. /**
  51115. * Internal only
  51116. * @ignore
  51117. */
  51118. ValueCondition._IsGreater = 2;
  51119. /**
  51120. * Internal only
  51121. * @ignore
  51122. */
  51123. ValueCondition._IsLesser = 3;
  51124. return ValueCondition;
  51125. }(Condition));
  51126. BABYLON.ValueCondition = ValueCondition;
  51127. /**
  51128. * Defines a predicate condition as an extension of Condition
  51129. */
  51130. var PredicateCondition = /** @class */ (function (_super) {
  51131. __extends(PredicateCondition, _super);
  51132. /**
  51133. * Creates a new {BABYLON.PredicateCondition}
  51134. * @param actionManager manager for the action the condition applies to
  51135. * @param predicate
  51136. */
  51137. function PredicateCondition(actionManager, predicate) {
  51138. var _this = _super.call(this, actionManager) || this;
  51139. _this.predicate = predicate;
  51140. return _this;
  51141. }
  51142. /**
  51143. * @returns the validity of the predicate condition
  51144. */
  51145. PredicateCondition.prototype.isValid = function () {
  51146. return this.predicate();
  51147. };
  51148. return PredicateCondition;
  51149. }(Condition));
  51150. BABYLON.PredicateCondition = PredicateCondition;
  51151. /**
  51152. * Defines a state condition as an extension of {BABYLON.Condition}
  51153. */
  51154. var StateCondition = /** @class */ (function (_super) {
  51155. __extends(StateCondition, _super);
  51156. /**
  51157. * Creates a new {BABYLON.StateCondition}
  51158. * @param actionManager manager for the action the condition applies to
  51159. * @param target of the condition
  51160. * @param value to compare with target state
  51161. */
  51162. function StateCondition(actionManager, target, value) {
  51163. var _this = _super.call(this, actionManager) || this;
  51164. _this.value = value;
  51165. _this._target = target;
  51166. return _this;
  51167. }
  51168. /**
  51169. * @returns the validity of the state
  51170. */
  51171. StateCondition.prototype.isValid = function () {
  51172. return this._target.state === this.value;
  51173. };
  51174. /**
  51175. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51176. * @returns serialization object
  51177. */
  51178. StateCondition.prototype.serialize = function () {
  51179. return this._serialize({
  51180. name: "StateCondition",
  51181. properties: [
  51182. BABYLON.Action._GetTargetProperty(this._target),
  51183. { name: "value", value: this.value }
  51184. ]
  51185. });
  51186. };
  51187. return StateCondition;
  51188. }(Condition));
  51189. BABYLON.StateCondition = StateCondition;
  51190. })(BABYLON || (BABYLON = {}));
  51191. //# sourceMappingURL=babylon.condition.js.map
  51192. "use strict";
  51193. var BABYLON;
  51194. (function (BABYLON) {
  51195. /**
  51196. * The action to be carried out following a trigger
  51197. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51198. */
  51199. var Action = /** @class */ (function () {
  51200. /**
  51201. * Creates a new Action
  51202. * @param triggerOptions the trigger, with or without parameters, for the action
  51203. * @param condition an optional determinant of action
  51204. */
  51205. function Action(triggerOptions, condition) {
  51206. this.triggerOptions = triggerOptions;
  51207. /**
  51208. * An event triggered prior to action being executed.
  51209. */
  51210. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51211. if (triggerOptions.parameter) {
  51212. this.trigger = triggerOptions.trigger;
  51213. this._triggerParameter = triggerOptions.parameter;
  51214. }
  51215. else {
  51216. this.trigger = triggerOptions;
  51217. }
  51218. this._nextActiveAction = this;
  51219. this._condition = condition;
  51220. }
  51221. /**
  51222. * Internal only
  51223. * @ignore
  51224. */
  51225. Action.prototype._prepare = function () {
  51226. };
  51227. /**
  51228. * Gets the trigger parameters
  51229. * @returns the trigger parameters
  51230. */
  51231. Action.prototype.getTriggerParameter = function () {
  51232. return this._triggerParameter;
  51233. };
  51234. /**
  51235. * Internal only - executes current action event
  51236. * @ignore
  51237. */
  51238. Action.prototype._executeCurrent = function (evt) {
  51239. if (this._nextActiveAction._condition) {
  51240. var condition = this._nextActiveAction._condition;
  51241. var currentRenderId = this._actionManager.getScene().getRenderId();
  51242. // We cache the current evaluation for the current frame
  51243. if (condition._evaluationId === currentRenderId) {
  51244. if (!condition._currentResult) {
  51245. return;
  51246. }
  51247. }
  51248. else {
  51249. condition._evaluationId = currentRenderId;
  51250. if (!condition.isValid()) {
  51251. condition._currentResult = false;
  51252. return;
  51253. }
  51254. condition._currentResult = true;
  51255. }
  51256. }
  51257. this.onBeforeExecuteObservable.notifyObservers(this);
  51258. this._nextActiveAction.execute(evt);
  51259. this.skipToNextActiveAction();
  51260. };
  51261. /**
  51262. * Execute placeholder for child classes
  51263. * @param evt optional action event
  51264. */
  51265. Action.prototype.execute = function (evt) {
  51266. };
  51267. /**
  51268. * Skips to next active action
  51269. */
  51270. Action.prototype.skipToNextActiveAction = function () {
  51271. if (this._nextActiveAction._child) {
  51272. if (!this._nextActiveAction._child._actionManager) {
  51273. this._nextActiveAction._child._actionManager = this._actionManager;
  51274. }
  51275. this._nextActiveAction = this._nextActiveAction._child;
  51276. }
  51277. else {
  51278. this._nextActiveAction = this;
  51279. }
  51280. };
  51281. /**
  51282. * Adds action to chain of actions, may be a DoNothingAction
  51283. * @param index The index of the attribute.
  51284. * @returns The action passed in
  51285. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51286. */
  51287. Action.prototype.then = function (action) {
  51288. this._child = action;
  51289. action._actionManager = this._actionManager;
  51290. action._prepare();
  51291. return action;
  51292. };
  51293. /**
  51294. * Internal only
  51295. * @ignore
  51296. */
  51297. Action.prototype._getProperty = function (propertyPath) {
  51298. return this._actionManager._getProperty(propertyPath);
  51299. };
  51300. /**
  51301. * Internal only
  51302. * @ignore
  51303. */
  51304. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51305. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51306. };
  51307. /**
  51308. * Serialize placeholder for child classes
  51309. * @param parent of child
  51310. * @returns the serialized object
  51311. */
  51312. Action.prototype.serialize = function (parent) {
  51313. };
  51314. /**
  51315. * Internal only called by serialize
  51316. * @ignore
  51317. */
  51318. Action.prototype._serialize = function (serializedAction, parent) {
  51319. var serializationObject = {
  51320. type: 1,
  51321. children: [],
  51322. name: serializedAction.name,
  51323. properties: serializedAction.properties || []
  51324. };
  51325. // Serialize child
  51326. if (this._child) {
  51327. this._child.serialize(serializationObject);
  51328. }
  51329. // Check if "this" has a condition
  51330. if (this._condition) {
  51331. var serializedCondition = this._condition.serialize();
  51332. serializedCondition.children.push(serializationObject);
  51333. if (parent) {
  51334. parent.children.push(serializedCondition);
  51335. }
  51336. return serializedCondition;
  51337. }
  51338. if (parent) {
  51339. parent.children.push(serializationObject);
  51340. }
  51341. return serializationObject;
  51342. };
  51343. /**
  51344. * Internal only
  51345. * @ignore
  51346. */
  51347. Action._SerializeValueAsString = function (value) {
  51348. if (typeof value === "number") {
  51349. return value.toString();
  51350. }
  51351. if (typeof value === "boolean") {
  51352. return value ? "true" : "false";
  51353. }
  51354. if (value instanceof BABYLON.Vector2) {
  51355. return value.x + ", " + value.y;
  51356. }
  51357. if (value instanceof BABYLON.Vector3) {
  51358. return value.x + ", " + value.y + ", " + value.z;
  51359. }
  51360. if (value instanceof BABYLON.Color3) {
  51361. return value.r + ", " + value.g + ", " + value.b;
  51362. }
  51363. if (value instanceof BABYLON.Color4) {
  51364. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51365. }
  51366. return value; // string
  51367. };
  51368. /**
  51369. * Internal only
  51370. * @ignore
  51371. */
  51372. Action._GetTargetProperty = function (target) {
  51373. return {
  51374. name: "target",
  51375. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51376. : target instanceof BABYLON.Light ? "LightProperties"
  51377. : target instanceof BABYLON.Camera ? "CameraProperties"
  51378. : "SceneProperties",
  51379. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51380. };
  51381. };
  51382. return Action;
  51383. }());
  51384. BABYLON.Action = Action;
  51385. })(BABYLON || (BABYLON = {}));
  51386. //# sourceMappingURL=babylon.action.js.map
  51387. "use strict";
  51388. var BABYLON;
  51389. (function (BABYLON) {
  51390. /**
  51391. * ActionEvent is the event being sent when an action is triggered.
  51392. */
  51393. var ActionEvent = /** @class */ (function () {
  51394. /**
  51395. * @param source The mesh or sprite that triggered the action.
  51396. * @param pointerX The X mouse cursor position at the time of the event
  51397. * @param pointerY The Y mouse cursor position at the time of the event
  51398. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51399. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51400. */
  51401. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  51402. this.source = source;
  51403. this.pointerX = pointerX;
  51404. this.pointerY = pointerY;
  51405. this.meshUnderPointer = meshUnderPointer;
  51406. this.sourceEvent = sourceEvent;
  51407. this.additionalData = additionalData;
  51408. }
  51409. /**
  51410. * Helper function to auto-create an ActionEvent from a source mesh.
  51411. * @param source The source mesh that triggered the event
  51412. * @param evt {Event} The original (browser) event
  51413. */
  51414. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51415. var scene = source.getScene();
  51416. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51417. };
  51418. /**
  51419. * Helper function to auto-create an ActionEvent from a source mesh.
  51420. * @param source The source sprite that triggered the event
  51421. * @param scene Scene associated with the sprite
  51422. * @param evt {Event} The original (browser) event
  51423. */
  51424. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51425. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51426. };
  51427. /**
  51428. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51429. * @param scene the scene where the event occurred
  51430. * @param evt {Event} The original (browser) event
  51431. */
  51432. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51433. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51434. };
  51435. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51436. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51437. };
  51438. return ActionEvent;
  51439. }());
  51440. BABYLON.ActionEvent = ActionEvent;
  51441. /**
  51442. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51443. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51444. */
  51445. var ActionManager = /** @class */ (function () {
  51446. function ActionManager(scene) {
  51447. // Members
  51448. this.actions = new Array();
  51449. this.hoverCursor = '';
  51450. this._scene = scene;
  51451. scene._actionManagers.push(this);
  51452. }
  51453. Object.defineProperty(ActionManager, "NothingTrigger", {
  51454. get: function () {
  51455. return ActionManager._NothingTrigger;
  51456. },
  51457. enumerable: true,
  51458. configurable: true
  51459. });
  51460. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51461. get: function () {
  51462. return ActionManager._OnPickTrigger;
  51463. },
  51464. enumerable: true,
  51465. configurable: true
  51466. });
  51467. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51468. get: function () {
  51469. return ActionManager._OnLeftPickTrigger;
  51470. },
  51471. enumerable: true,
  51472. configurable: true
  51473. });
  51474. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51475. get: function () {
  51476. return ActionManager._OnRightPickTrigger;
  51477. },
  51478. enumerable: true,
  51479. configurable: true
  51480. });
  51481. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51482. get: function () {
  51483. return ActionManager._OnCenterPickTrigger;
  51484. },
  51485. enumerable: true,
  51486. configurable: true
  51487. });
  51488. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51489. get: function () {
  51490. return ActionManager._OnPickDownTrigger;
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  51496. get: function () {
  51497. return ActionManager._OnDoublePickTrigger;
  51498. },
  51499. enumerable: true,
  51500. configurable: true
  51501. });
  51502. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  51503. get: function () {
  51504. return ActionManager._OnPickUpTrigger;
  51505. },
  51506. enumerable: true,
  51507. configurable: true
  51508. });
  51509. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  51510. /// This trigger will only be raised if you also declared a OnPickDown
  51511. get: function () {
  51512. return ActionManager._OnPickOutTrigger;
  51513. },
  51514. enumerable: true,
  51515. configurable: true
  51516. });
  51517. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  51518. get: function () {
  51519. return ActionManager._OnLongPressTrigger;
  51520. },
  51521. enumerable: true,
  51522. configurable: true
  51523. });
  51524. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  51525. get: function () {
  51526. return ActionManager._OnPointerOverTrigger;
  51527. },
  51528. enumerable: true,
  51529. configurable: true
  51530. });
  51531. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  51532. get: function () {
  51533. return ActionManager._OnPointerOutTrigger;
  51534. },
  51535. enumerable: true,
  51536. configurable: true
  51537. });
  51538. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  51539. get: function () {
  51540. return ActionManager._OnEveryFrameTrigger;
  51541. },
  51542. enumerable: true,
  51543. configurable: true
  51544. });
  51545. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  51546. get: function () {
  51547. return ActionManager._OnIntersectionEnterTrigger;
  51548. },
  51549. enumerable: true,
  51550. configurable: true
  51551. });
  51552. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  51553. get: function () {
  51554. return ActionManager._OnIntersectionExitTrigger;
  51555. },
  51556. enumerable: true,
  51557. configurable: true
  51558. });
  51559. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  51560. get: function () {
  51561. return ActionManager._OnKeyDownTrigger;
  51562. },
  51563. enumerable: true,
  51564. configurable: true
  51565. });
  51566. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  51567. get: function () {
  51568. return ActionManager._OnKeyUpTrigger;
  51569. },
  51570. enumerable: true,
  51571. configurable: true
  51572. });
  51573. // Methods
  51574. ActionManager.prototype.dispose = function () {
  51575. var index = this._scene._actionManagers.indexOf(this);
  51576. for (var i = 0; i < this.actions.length; i++) {
  51577. var action = this.actions[i];
  51578. ActionManager.Triggers[action.trigger]--;
  51579. if (ActionManager.Triggers[action.trigger] === 0) {
  51580. delete ActionManager.Triggers[action.trigger];
  51581. }
  51582. }
  51583. if (index > -1) {
  51584. this._scene._actionManagers.splice(index, 1);
  51585. }
  51586. };
  51587. ActionManager.prototype.getScene = function () {
  51588. return this._scene;
  51589. };
  51590. /**
  51591. * Does this action manager handles actions of any of the given triggers
  51592. * @param {number[]} triggers - the triggers to be tested
  51593. * @return {boolean} whether one (or more) of the triggers is handeled
  51594. */
  51595. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  51596. for (var index = 0; index < this.actions.length; index++) {
  51597. var action = this.actions[index];
  51598. if (triggers.indexOf(action.trigger) > -1) {
  51599. return true;
  51600. }
  51601. }
  51602. return false;
  51603. };
  51604. /**
  51605. * Does this action manager handles actions of a given trigger
  51606. * @param {number} trigger - the trigger to be tested
  51607. * @return {boolean} whether the trigger is handeled
  51608. */
  51609. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  51610. for (var index = 0; index < this.actions.length; index++) {
  51611. var action = this.actions[index];
  51612. if (action.trigger === trigger) {
  51613. return true;
  51614. }
  51615. }
  51616. return false;
  51617. };
  51618. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  51619. /**
  51620. * Does this action manager has pointer triggers
  51621. * @return {boolean} whether or not it has pointer triggers
  51622. */
  51623. get: function () {
  51624. for (var index = 0; index < this.actions.length; index++) {
  51625. var action = this.actions[index];
  51626. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  51627. return true;
  51628. }
  51629. }
  51630. return false;
  51631. },
  51632. enumerable: true,
  51633. configurable: true
  51634. });
  51635. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  51636. /**
  51637. * Does this action manager has pick triggers
  51638. * @return {boolean} whether or not it has pick triggers
  51639. */
  51640. get: function () {
  51641. for (var index = 0; index < this.actions.length; index++) {
  51642. var action = this.actions[index];
  51643. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  51644. return true;
  51645. }
  51646. }
  51647. return false;
  51648. },
  51649. enumerable: true,
  51650. configurable: true
  51651. });
  51652. Object.defineProperty(ActionManager, "HasTriggers", {
  51653. /**
  51654. * Does exist one action manager with at least one trigger
  51655. * @return {boolean} whether or not it exists one action manager with one trigger
  51656. **/
  51657. get: function () {
  51658. for (var t in ActionManager.Triggers) {
  51659. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51660. return true;
  51661. }
  51662. }
  51663. return false;
  51664. },
  51665. enumerable: true,
  51666. configurable: true
  51667. });
  51668. Object.defineProperty(ActionManager, "HasPickTriggers", {
  51669. /**
  51670. * Does exist one action manager with at least one pick trigger
  51671. * @return {boolean} whether or not it exists one action manager with one pick trigger
  51672. **/
  51673. get: function () {
  51674. for (var t in ActionManager.Triggers) {
  51675. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51676. var t_int = parseInt(t);
  51677. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  51678. return true;
  51679. }
  51680. }
  51681. }
  51682. return false;
  51683. },
  51684. enumerable: true,
  51685. configurable: true
  51686. });
  51687. /**
  51688. * Does exist one action manager that handles actions of a given trigger
  51689. * @param {number} trigger - the trigger to be tested
  51690. * @return {boolean} whether the trigger is handeled by at least one action manager
  51691. **/
  51692. ActionManager.HasSpecificTrigger = function (trigger) {
  51693. for (var t in ActionManager.Triggers) {
  51694. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51695. var t_int = parseInt(t);
  51696. if (t_int === trigger) {
  51697. return true;
  51698. }
  51699. }
  51700. }
  51701. return false;
  51702. };
  51703. /**
  51704. * Registers an action to this action manager
  51705. * @param {BABYLON.Action} action - the action to be registered
  51706. * @return {BABYLON.Action} the action amended (prepared) after registration
  51707. */
  51708. ActionManager.prototype.registerAction = function (action) {
  51709. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  51710. if (this.getScene().actionManager !== this) {
  51711. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  51712. return null;
  51713. }
  51714. }
  51715. this.actions.push(action);
  51716. if (ActionManager.Triggers[action.trigger]) {
  51717. ActionManager.Triggers[action.trigger]++;
  51718. }
  51719. else {
  51720. ActionManager.Triggers[action.trigger] = 1;
  51721. }
  51722. action._actionManager = this;
  51723. action._prepare();
  51724. return action;
  51725. };
  51726. /**
  51727. * Unregisters an action to this action manager
  51728. * @param action The action to be unregistered
  51729. * @return whether the action has been unregistered
  51730. */
  51731. ActionManager.prototype.unregisterAction = function (action) {
  51732. var index = this.actions.indexOf(action);
  51733. if (index !== -1) {
  51734. this.actions.splice(index, 1);
  51735. ActionManager.Triggers[action.trigger] -= 1;
  51736. if (ActionManager.Triggers[action.trigger] === 0) {
  51737. delete ActionManager.Triggers[action.trigger];
  51738. }
  51739. delete action._actionManager;
  51740. return true;
  51741. }
  51742. return false;
  51743. };
  51744. /**
  51745. * Process a specific trigger
  51746. * @param {number} trigger - the trigger to process
  51747. * @param evt {BABYLON.ActionEvent} the event details to be processed
  51748. */
  51749. ActionManager.prototype.processTrigger = function (trigger, evt) {
  51750. for (var index = 0; index < this.actions.length; index++) {
  51751. var action = this.actions[index];
  51752. if (action.trigger === trigger) {
  51753. if (evt) {
  51754. if (trigger === ActionManager.OnKeyUpTrigger
  51755. || trigger === ActionManager.OnKeyDownTrigger) {
  51756. var parameter = action.getTriggerParameter();
  51757. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  51758. if (!parameter.toLowerCase) {
  51759. continue;
  51760. }
  51761. var lowerCase = parameter.toLowerCase();
  51762. if (lowerCase !== evt.sourceEvent.key) {
  51763. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  51764. var actualkey = String.fromCharCode(unicode).toLowerCase();
  51765. if (actualkey !== lowerCase) {
  51766. continue;
  51767. }
  51768. }
  51769. }
  51770. }
  51771. }
  51772. action._executeCurrent(evt);
  51773. }
  51774. }
  51775. };
  51776. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  51777. var properties = propertyPath.split(".");
  51778. for (var index = 0; index < properties.length - 1; index++) {
  51779. target = target[properties[index]];
  51780. }
  51781. return target;
  51782. };
  51783. ActionManager.prototype._getProperty = function (propertyPath) {
  51784. var properties = propertyPath.split(".");
  51785. return properties[properties.length - 1];
  51786. };
  51787. ActionManager.prototype.serialize = function (name) {
  51788. var root = {
  51789. children: new Array(),
  51790. name: name,
  51791. type: 3,
  51792. properties: new Array() // Empty for root but required
  51793. };
  51794. for (var i = 0; i < this.actions.length; i++) {
  51795. var triggerObject = {
  51796. type: 0,
  51797. children: new Array(),
  51798. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  51799. properties: new Array()
  51800. };
  51801. var triggerOptions = this.actions[i].triggerOptions;
  51802. if (triggerOptions && typeof triggerOptions !== "number") {
  51803. if (triggerOptions.parameter instanceof BABYLON.Node) {
  51804. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  51805. }
  51806. else {
  51807. var parameter = {};
  51808. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  51809. if (triggerOptions.parameter.mesh) {
  51810. parameter._meshId = triggerOptions.parameter.mesh.id;
  51811. }
  51812. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  51813. }
  51814. }
  51815. // Serialize child action, recursively
  51816. this.actions[i].serialize(triggerObject);
  51817. // Add serialized trigger
  51818. root.children.push(triggerObject);
  51819. }
  51820. return root;
  51821. };
  51822. ActionManager.Parse = function (parsedActions, object, scene) {
  51823. var actionManager = new ActionManager(scene);
  51824. if (object === null)
  51825. scene.actionManager = actionManager;
  51826. else
  51827. object.actionManager = actionManager;
  51828. // instanciate a new object
  51829. var instanciate = function (name, params) {
  51830. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  51831. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  51832. newInstance.constructor.apply(newInstance, params);
  51833. return newInstance;
  51834. };
  51835. var parseParameter = function (name, value, target, propertyPath) {
  51836. if (propertyPath === null) {
  51837. // String, boolean or float
  51838. var floatValue = parseFloat(value);
  51839. if (value === "true" || value === "false")
  51840. return value === "true";
  51841. else
  51842. return isNaN(floatValue) ? value : floatValue;
  51843. }
  51844. var effectiveTarget = propertyPath.split(".");
  51845. var values = value.split(",");
  51846. // Get effective Target
  51847. for (var i = 0; i < effectiveTarget.length; i++) {
  51848. target = target[effectiveTarget[i]];
  51849. }
  51850. // Return appropriate value with its type
  51851. if (typeof (target) === "boolean")
  51852. return values[0] === "true";
  51853. if (typeof (target) === "string")
  51854. return values[0];
  51855. // Parameters with multiple values such as Vector3 etc.
  51856. var split = new Array();
  51857. for (var i = 0; i < values.length; i++)
  51858. split.push(parseFloat(values[i]));
  51859. if (target instanceof BABYLON.Vector3)
  51860. return BABYLON.Vector3.FromArray(split);
  51861. if (target instanceof BABYLON.Vector4)
  51862. return BABYLON.Vector4.FromArray(split);
  51863. if (target instanceof BABYLON.Color3)
  51864. return BABYLON.Color3.FromArray(split);
  51865. if (target instanceof BABYLON.Color4)
  51866. return BABYLON.Color4.FromArray(split);
  51867. return parseFloat(values[0]);
  51868. };
  51869. // traverse graph per trigger
  51870. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  51871. if (combineArray === void 0) { combineArray = null; }
  51872. if (parsedAction.detached)
  51873. return;
  51874. var parameters = new Array();
  51875. var target = null;
  51876. var propertyPath = null;
  51877. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  51878. // Parameters
  51879. if (parsedAction.type === 2)
  51880. parameters.push(actionManager);
  51881. else
  51882. parameters.push(trigger);
  51883. if (combine) {
  51884. var actions = new Array();
  51885. for (var j = 0; j < parsedAction.combine.length; j++) {
  51886. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  51887. }
  51888. parameters.push(actions);
  51889. }
  51890. else {
  51891. for (var i = 0; i < parsedAction.properties.length; i++) {
  51892. var value = parsedAction.properties[i].value;
  51893. var name = parsedAction.properties[i].name;
  51894. var targetType = parsedAction.properties[i].targetType;
  51895. if (name === "target")
  51896. if (targetType !== null && targetType === "SceneProperties")
  51897. value = target = scene;
  51898. else
  51899. value = target = scene.getNodeByName(value);
  51900. else if (name === "parent")
  51901. value = scene.getNodeByName(value);
  51902. else if (name === "sound")
  51903. value = scene.getSoundByName(value);
  51904. else if (name !== "propertyPath") {
  51905. if (parsedAction.type === 2 && name === "operator")
  51906. value = BABYLON.ValueCondition[value];
  51907. else
  51908. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  51909. }
  51910. else {
  51911. propertyPath = value;
  51912. }
  51913. parameters.push(value);
  51914. }
  51915. }
  51916. if (combineArray === null) {
  51917. parameters.push(condition);
  51918. }
  51919. else {
  51920. parameters.push(null);
  51921. }
  51922. // If interpolate value action
  51923. if (parsedAction.name === "InterpolateValueAction") {
  51924. var param = parameters[parameters.length - 2];
  51925. parameters[parameters.length - 1] = param;
  51926. parameters[parameters.length - 2] = condition;
  51927. }
  51928. // Action or condition(s) and not CombineAction
  51929. var newAction = instanciate(parsedAction.name, parameters);
  51930. if (newAction instanceof BABYLON.Condition && condition !== null) {
  51931. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  51932. if (action)
  51933. action.then(nothing);
  51934. else
  51935. actionManager.registerAction(nothing);
  51936. action = nothing;
  51937. }
  51938. if (combineArray === null) {
  51939. if (newAction instanceof BABYLON.Condition) {
  51940. condition = newAction;
  51941. newAction = action;
  51942. }
  51943. else {
  51944. condition = null;
  51945. if (action)
  51946. action.then(newAction);
  51947. else
  51948. actionManager.registerAction(newAction);
  51949. }
  51950. }
  51951. else {
  51952. combineArray.push(newAction);
  51953. }
  51954. for (var i = 0; i < parsedAction.children.length; i++)
  51955. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  51956. };
  51957. // triggers
  51958. for (var i = 0; i < parsedActions.children.length; i++) {
  51959. var triggerParams;
  51960. var trigger = parsedActions.children[i];
  51961. if (trigger.properties.length > 0) {
  51962. var param = trigger.properties[0].value;
  51963. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  51964. if (value._meshId) {
  51965. value.mesh = scene.getMeshByID(value._meshId);
  51966. }
  51967. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  51968. }
  51969. else
  51970. triggerParams = ActionManager[trigger.name];
  51971. for (var j = 0; j < trigger.children.length; j++) {
  51972. if (!trigger.detached)
  51973. traverse(trigger.children[j], triggerParams, null, null);
  51974. }
  51975. }
  51976. };
  51977. ActionManager.GetTriggerName = function (trigger) {
  51978. switch (trigger) {
  51979. case 0: return "NothingTrigger";
  51980. case 1: return "OnPickTrigger";
  51981. case 2: return "OnLeftPickTrigger";
  51982. case 3: return "OnRightPickTrigger";
  51983. case 4: return "OnCenterPickTrigger";
  51984. case 5: return "OnPickDownTrigger";
  51985. case 6: return "OnPickUpTrigger";
  51986. case 7: return "OnLongPressTrigger";
  51987. case 8: return "OnPointerOverTrigger";
  51988. case 9: return "OnPointerOutTrigger";
  51989. case 10: return "OnEveryFrameTrigger";
  51990. case 11: return "OnIntersectionEnterTrigger";
  51991. case 12: return "OnIntersectionExitTrigger";
  51992. case 13: return "OnKeyDownTrigger";
  51993. case 14: return "OnKeyUpTrigger";
  51994. case 15: return "OnPickOutTrigger";
  51995. default: return "";
  51996. }
  51997. };
  51998. // Statics
  51999. ActionManager._NothingTrigger = 0;
  52000. ActionManager._OnPickTrigger = 1;
  52001. ActionManager._OnLeftPickTrigger = 2;
  52002. ActionManager._OnRightPickTrigger = 3;
  52003. ActionManager._OnCenterPickTrigger = 4;
  52004. ActionManager._OnPickDownTrigger = 5;
  52005. ActionManager._OnDoublePickTrigger = 6;
  52006. ActionManager._OnPickUpTrigger = 7;
  52007. ActionManager._OnLongPressTrigger = 8;
  52008. ActionManager._OnPointerOverTrigger = 9;
  52009. ActionManager._OnPointerOutTrigger = 10;
  52010. ActionManager._OnEveryFrameTrigger = 11;
  52011. ActionManager._OnIntersectionEnterTrigger = 12;
  52012. ActionManager._OnIntersectionExitTrigger = 13;
  52013. ActionManager._OnKeyDownTrigger = 14;
  52014. ActionManager._OnKeyUpTrigger = 15;
  52015. ActionManager._OnPickOutTrigger = 16;
  52016. ActionManager.Triggers = {};
  52017. return ActionManager;
  52018. }());
  52019. BABYLON.ActionManager = ActionManager;
  52020. })(BABYLON || (BABYLON = {}));
  52021. //# sourceMappingURL=babylon.actionManager.js.map
  52022. "use strict";
  52023. var BABYLON;
  52024. (function (BABYLON) {
  52025. var InterpolateValueAction = /** @class */ (function (_super) {
  52026. __extends(InterpolateValueAction, _super);
  52027. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52028. if (duration === void 0) { duration = 1000; }
  52029. var _this = _super.call(this, triggerOptions, condition) || this;
  52030. _this.propertyPath = propertyPath;
  52031. _this.value = value;
  52032. _this.duration = duration;
  52033. _this.stopOtherAnimations = stopOtherAnimations;
  52034. _this.onInterpolationDone = onInterpolationDone;
  52035. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52036. _this._target = _this._effectiveTarget = target;
  52037. return _this;
  52038. }
  52039. InterpolateValueAction.prototype._prepare = function () {
  52040. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52041. this._property = this._getProperty(this.propertyPath);
  52042. };
  52043. InterpolateValueAction.prototype.execute = function () {
  52044. var _this = this;
  52045. var scene = this._actionManager.getScene();
  52046. var keys = [
  52047. {
  52048. frame: 0,
  52049. value: this._effectiveTarget[this._property]
  52050. }, {
  52051. frame: 100,
  52052. value: this.value
  52053. }
  52054. ];
  52055. var dataType;
  52056. if (typeof this.value === "number") {
  52057. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52058. }
  52059. else if (this.value instanceof BABYLON.Color3) {
  52060. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52061. }
  52062. else if (this.value instanceof BABYLON.Vector3) {
  52063. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52064. }
  52065. else if (this.value instanceof BABYLON.Matrix) {
  52066. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52067. }
  52068. else if (this.value instanceof BABYLON.Quaternion) {
  52069. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52070. }
  52071. else {
  52072. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52073. return;
  52074. }
  52075. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52076. animation.setKeys(keys);
  52077. if (this.stopOtherAnimations) {
  52078. scene.stopAnimation(this._effectiveTarget);
  52079. }
  52080. var wrapper = function () {
  52081. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52082. if (_this.onInterpolationDone) {
  52083. _this.onInterpolationDone();
  52084. }
  52085. };
  52086. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52087. };
  52088. InterpolateValueAction.prototype.serialize = function (parent) {
  52089. return _super.prototype._serialize.call(this, {
  52090. name: "InterpolateValueAction",
  52091. properties: [
  52092. BABYLON.Action._GetTargetProperty(this._target),
  52093. { name: "propertyPath", value: this.propertyPath },
  52094. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52095. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52096. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52097. ]
  52098. }, parent);
  52099. };
  52100. return InterpolateValueAction;
  52101. }(BABYLON.Action));
  52102. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52103. })(BABYLON || (BABYLON = {}));
  52104. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52105. "use strict";
  52106. var BABYLON;
  52107. (function (BABYLON) {
  52108. var SwitchBooleanAction = /** @class */ (function (_super) {
  52109. __extends(SwitchBooleanAction, _super);
  52110. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52111. var _this = _super.call(this, triggerOptions, condition) || this;
  52112. _this.propertyPath = propertyPath;
  52113. _this._target = _this._effectiveTarget = target;
  52114. return _this;
  52115. }
  52116. SwitchBooleanAction.prototype._prepare = function () {
  52117. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52118. this._property = this._getProperty(this.propertyPath);
  52119. };
  52120. SwitchBooleanAction.prototype.execute = function () {
  52121. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52122. };
  52123. SwitchBooleanAction.prototype.serialize = function (parent) {
  52124. return _super.prototype._serialize.call(this, {
  52125. name: "SwitchBooleanAction",
  52126. properties: [
  52127. BABYLON.Action._GetTargetProperty(this._target),
  52128. { name: "propertyPath", value: this.propertyPath }
  52129. ]
  52130. }, parent);
  52131. };
  52132. return SwitchBooleanAction;
  52133. }(BABYLON.Action));
  52134. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52135. var SetStateAction = /** @class */ (function (_super) {
  52136. __extends(SetStateAction, _super);
  52137. function SetStateAction(triggerOptions, target, value, condition) {
  52138. var _this = _super.call(this, triggerOptions, condition) || this;
  52139. _this.value = value;
  52140. _this._target = target;
  52141. return _this;
  52142. }
  52143. SetStateAction.prototype.execute = function () {
  52144. this._target.state = this.value;
  52145. };
  52146. SetStateAction.prototype.serialize = function (parent) {
  52147. return _super.prototype._serialize.call(this, {
  52148. name: "SetStateAction",
  52149. properties: [
  52150. BABYLON.Action._GetTargetProperty(this._target),
  52151. { name: "value", value: this.value }
  52152. ]
  52153. }, parent);
  52154. };
  52155. return SetStateAction;
  52156. }(BABYLON.Action));
  52157. BABYLON.SetStateAction = SetStateAction;
  52158. var SetValueAction = /** @class */ (function (_super) {
  52159. __extends(SetValueAction, _super);
  52160. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52161. var _this = _super.call(this, triggerOptions, condition) || this;
  52162. _this.propertyPath = propertyPath;
  52163. _this.value = value;
  52164. _this._target = _this._effectiveTarget = target;
  52165. return _this;
  52166. }
  52167. SetValueAction.prototype._prepare = function () {
  52168. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52169. this._property = this._getProperty(this.propertyPath);
  52170. };
  52171. SetValueAction.prototype.execute = function () {
  52172. this._effectiveTarget[this._property] = this.value;
  52173. if (this._target.markAsDirty) {
  52174. this._target.markAsDirty(this._property);
  52175. }
  52176. };
  52177. SetValueAction.prototype.serialize = function (parent) {
  52178. return _super.prototype._serialize.call(this, {
  52179. name: "SetValueAction",
  52180. properties: [
  52181. BABYLON.Action._GetTargetProperty(this._target),
  52182. { name: "propertyPath", value: this.propertyPath },
  52183. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52184. ]
  52185. }, parent);
  52186. };
  52187. return SetValueAction;
  52188. }(BABYLON.Action));
  52189. BABYLON.SetValueAction = SetValueAction;
  52190. var IncrementValueAction = /** @class */ (function (_super) {
  52191. __extends(IncrementValueAction, _super);
  52192. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52193. var _this = _super.call(this, triggerOptions, condition) || this;
  52194. _this.propertyPath = propertyPath;
  52195. _this.value = value;
  52196. _this._target = _this._effectiveTarget = target;
  52197. return _this;
  52198. }
  52199. IncrementValueAction.prototype._prepare = function () {
  52200. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52201. this._property = this._getProperty(this.propertyPath);
  52202. if (typeof this._effectiveTarget[this._property] !== "number") {
  52203. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52204. }
  52205. };
  52206. IncrementValueAction.prototype.execute = function () {
  52207. this._effectiveTarget[this._property] += this.value;
  52208. if (this._target.markAsDirty) {
  52209. this._target.markAsDirty(this._property);
  52210. }
  52211. };
  52212. IncrementValueAction.prototype.serialize = function (parent) {
  52213. return _super.prototype._serialize.call(this, {
  52214. name: "IncrementValueAction",
  52215. properties: [
  52216. BABYLON.Action._GetTargetProperty(this._target),
  52217. { name: "propertyPath", value: this.propertyPath },
  52218. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52219. ]
  52220. }, parent);
  52221. };
  52222. return IncrementValueAction;
  52223. }(BABYLON.Action));
  52224. BABYLON.IncrementValueAction = IncrementValueAction;
  52225. var PlayAnimationAction = /** @class */ (function (_super) {
  52226. __extends(PlayAnimationAction, _super);
  52227. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52228. var _this = _super.call(this, triggerOptions, condition) || this;
  52229. _this.from = from;
  52230. _this.to = to;
  52231. _this.loop = loop;
  52232. _this._target = target;
  52233. return _this;
  52234. }
  52235. PlayAnimationAction.prototype._prepare = function () {
  52236. };
  52237. PlayAnimationAction.prototype.execute = function () {
  52238. var scene = this._actionManager.getScene();
  52239. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52240. };
  52241. PlayAnimationAction.prototype.serialize = function (parent) {
  52242. return _super.prototype._serialize.call(this, {
  52243. name: "PlayAnimationAction",
  52244. properties: [
  52245. BABYLON.Action._GetTargetProperty(this._target),
  52246. { name: "from", value: String(this.from) },
  52247. { name: "to", value: String(this.to) },
  52248. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52249. ]
  52250. }, parent);
  52251. };
  52252. return PlayAnimationAction;
  52253. }(BABYLON.Action));
  52254. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52255. var StopAnimationAction = /** @class */ (function (_super) {
  52256. __extends(StopAnimationAction, _super);
  52257. function StopAnimationAction(triggerOptions, target, condition) {
  52258. var _this = _super.call(this, triggerOptions, condition) || this;
  52259. _this._target = target;
  52260. return _this;
  52261. }
  52262. StopAnimationAction.prototype._prepare = function () {
  52263. };
  52264. StopAnimationAction.prototype.execute = function () {
  52265. var scene = this._actionManager.getScene();
  52266. scene.stopAnimation(this._target);
  52267. };
  52268. StopAnimationAction.prototype.serialize = function (parent) {
  52269. return _super.prototype._serialize.call(this, {
  52270. name: "StopAnimationAction",
  52271. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52272. }, parent);
  52273. };
  52274. return StopAnimationAction;
  52275. }(BABYLON.Action));
  52276. BABYLON.StopAnimationAction = StopAnimationAction;
  52277. var DoNothingAction = /** @class */ (function (_super) {
  52278. __extends(DoNothingAction, _super);
  52279. function DoNothingAction(triggerOptions, condition) {
  52280. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52281. return _super.call(this, triggerOptions, condition) || this;
  52282. }
  52283. DoNothingAction.prototype.execute = function () {
  52284. };
  52285. DoNothingAction.prototype.serialize = function (parent) {
  52286. return _super.prototype._serialize.call(this, {
  52287. name: "DoNothingAction",
  52288. properties: []
  52289. }, parent);
  52290. };
  52291. return DoNothingAction;
  52292. }(BABYLON.Action));
  52293. BABYLON.DoNothingAction = DoNothingAction;
  52294. var CombineAction = /** @class */ (function (_super) {
  52295. __extends(CombineAction, _super);
  52296. function CombineAction(triggerOptions, children, condition) {
  52297. var _this = _super.call(this, triggerOptions, condition) || this;
  52298. _this.children = children;
  52299. return _this;
  52300. }
  52301. CombineAction.prototype._prepare = function () {
  52302. for (var index = 0; index < this.children.length; index++) {
  52303. this.children[index]._actionManager = this._actionManager;
  52304. this.children[index]._prepare();
  52305. }
  52306. };
  52307. CombineAction.prototype.execute = function (evt) {
  52308. for (var index = 0; index < this.children.length; index++) {
  52309. this.children[index].execute(evt);
  52310. }
  52311. };
  52312. CombineAction.prototype.serialize = function (parent) {
  52313. var serializationObject = _super.prototype._serialize.call(this, {
  52314. name: "CombineAction",
  52315. properties: [],
  52316. combine: []
  52317. }, parent);
  52318. for (var i = 0; i < this.children.length; i++) {
  52319. serializationObject.combine.push(this.children[i].serialize(null));
  52320. }
  52321. return serializationObject;
  52322. };
  52323. return CombineAction;
  52324. }(BABYLON.Action));
  52325. BABYLON.CombineAction = CombineAction;
  52326. var ExecuteCodeAction = /** @class */ (function (_super) {
  52327. __extends(ExecuteCodeAction, _super);
  52328. function ExecuteCodeAction(triggerOptions, func, condition) {
  52329. var _this = _super.call(this, triggerOptions, condition) || this;
  52330. _this.func = func;
  52331. return _this;
  52332. }
  52333. ExecuteCodeAction.prototype.execute = function (evt) {
  52334. this.func(evt);
  52335. };
  52336. return ExecuteCodeAction;
  52337. }(BABYLON.Action));
  52338. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52339. var SetParentAction = /** @class */ (function (_super) {
  52340. __extends(SetParentAction, _super);
  52341. function SetParentAction(triggerOptions, target, parent, condition) {
  52342. var _this = _super.call(this, triggerOptions, condition) || this;
  52343. _this._target = target;
  52344. _this._parent = parent;
  52345. return _this;
  52346. }
  52347. SetParentAction.prototype._prepare = function () {
  52348. };
  52349. SetParentAction.prototype.execute = function () {
  52350. if (this._target.parent === this._parent) {
  52351. return;
  52352. }
  52353. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52354. invertParentWorldMatrix.invert();
  52355. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52356. this._target.parent = this._parent;
  52357. };
  52358. SetParentAction.prototype.serialize = function (parent) {
  52359. return _super.prototype._serialize.call(this, {
  52360. name: "SetParentAction",
  52361. properties: [
  52362. BABYLON.Action._GetTargetProperty(this._target),
  52363. BABYLON.Action._GetTargetProperty(this._parent),
  52364. ]
  52365. }, parent);
  52366. };
  52367. return SetParentAction;
  52368. }(BABYLON.Action));
  52369. BABYLON.SetParentAction = SetParentAction;
  52370. var PlaySoundAction = /** @class */ (function (_super) {
  52371. __extends(PlaySoundAction, _super);
  52372. function PlaySoundAction(triggerOptions, sound, condition) {
  52373. var _this = _super.call(this, triggerOptions, condition) || this;
  52374. _this._sound = sound;
  52375. return _this;
  52376. }
  52377. PlaySoundAction.prototype._prepare = function () {
  52378. };
  52379. PlaySoundAction.prototype.execute = function () {
  52380. if (this._sound !== undefined)
  52381. this._sound.play();
  52382. };
  52383. PlaySoundAction.prototype.serialize = function (parent) {
  52384. return _super.prototype._serialize.call(this, {
  52385. name: "PlaySoundAction",
  52386. properties: [{ name: "sound", value: this._sound.name }]
  52387. }, parent);
  52388. };
  52389. return PlaySoundAction;
  52390. }(BABYLON.Action));
  52391. BABYLON.PlaySoundAction = PlaySoundAction;
  52392. var StopSoundAction = /** @class */ (function (_super) {
  52393. __extends(StopSoundAction, _super);
  52394. function StopSoundAction(triggerOptions, sound, condition) {
  52395. var _this = _super.call(this, triggerOptions, condition) || this;
  52396. _this._sound = sound;
  52397. return _this;
  52398. }
  52399. StopSoundAction.prototype._prepare = function () {
  52400. };
  52401. StopSoundAction.prototype.execute = function () {
  52402. if (this._sound !== undefined)
  52403. this._sound.stop();
  52404. };
  52405. StopSoundAction.prototype.serialize = function (parent) {
  52406. return _super.prototype._serialize.call(this, {
  52407. name: "StopSoundAction",
  52408. properties: [{ name: "sound", value: this._sound.name }]
  52409. }, parent);
  52410. };
  52411. return StopSoundAction;
  52412. }(BABYLON.Action));
  52413. BABYLON.StopSoundAction = StopSoundAction;
  52414. })(BABYLON || (BABYLON = {}));
  52415. //# sourceMappingURL=babylon.directActions.js.map
  52416. "use strict";
  52417. var BABYLON;
  52418. (function (BABYLON) {
  52419. var SpriteManager = /** @class */ (function () {
  52420. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52421. if (epsilon === void 0) { epsilon = 0.01; }
  52422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52423. this.name = name;
  52424. this.sprites = new Array();
  52425. this.renderingGroupId = 0;
  52426. this.layerMask = 0x0FFFFFFF;
  52427. this.fogEnabled = true;
  52428. this.isPickable = false;
  52429. /**
  52430. * An event triggered when the manager is disposed.
  52431. */
  52432. this.onDisposeObservable = new BABYLON.Observable();
  52433. this._vertexBuffers = {};
  52434. this._capacity = capacity;
  52435. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52436. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52437. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52438. if (cellSize.width && cellSize.height) {
  52439. this.cellWidth = cellSize.width;
  52440. this.cellHeight = cellSize.height;
  52441. }
  52442. else if (cellSize !== undefined) {
  52443. this.cellWidth = cellSize;
  52444. this.cellHeight = cellSize;
  52445. }
  52446. else {
  52447. return;
  52448. }
  52449. this._epsilon = epsilon;
  52450. this._scene = scene;
  52451. this._scene.spriteManagers.push(this);
  52452. var indices = [];
  52453. var index = 0;
  52454. for (var count = 0; count < capacity; count++) {
  52455. indices.push(index);
  52456. indices.push(index + 1);
  52457. indices.push(index + 2);
  52458. indices.push(index);
  52459. indices.push(index + 2);
  52460. indices.push(index + 3);
  52461. index += 4;
  52462. }
  52463. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  52464. // VBO
  52465. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  52466. this._vertexData = new Float32Array(capacity * 16 * 4);
  52467. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  52468. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  52469. var options = this._buffer.createVertexBuffer("options", 4, 4);
  52470. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  52471. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  52472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52473. this._vertexBuffers["options"] = options;
  52474. this._vertexBuffers["cellInfo"] = cellInfo;
  52475. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52476. // Effects
  52477. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  52478. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  52479. }
  52480. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  52481. set: function (callback) {
  52482. if (this._onDisposeObserver) {
  52483. this.onDisposeObservable.remove(this._onDisposeObserver);
  52484. }
  52485. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52486. },
  52487. enumerable: true,
  52488. configurable: true
  52489. });
  52490. Object.defineProperty(SpriteManager.prototype, "texture", {
  52491. get: function () {
  52492. return this._spriteTexture;
  52493. },
  52494. set: function (value) {
  52495. this._spriteTexture = value;
  52496. },
  52497. enumerable: true,
  52498. configurable: true
  52499. });
  52500. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  52501. var arrayOffset = index * 16;
  52502. if (offsetX === 0)
  52503. offsetX = this._epsilon;
  52504. else if (offsetX === 1)
  52505. offsetX = 1 - this._epsilon;
  52506. if (offsetY === 0)
  52507. offsetY = this._epsilon;
  52508. else if (offsetY === 1)
  52509. offsetY = 1 - this._epsilon;
  52510. this._vertexData[arrayOffset] = sprite.position.x;
  52511. this._vertexData[arrayOffset + 1] = sprite.position.y;
  52512. this._vertexData[arrayOffset + 2] = sprite.position.z;
  52513. this._vertexData[arrayOffset + 3] = sprite.angle;
  52514. this._vertexData[arrayOffset + 4] = sprite.width;
  52515. this._vertexData[arrayOffset + 5] = sprite.height;
  52516. this._vertexData[arrayOffset + 6] = offsetX;
  52517. this._vertexData[arrayOffset + 7] = offsetY;
  52518. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  52519. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  52520. var offset = (sprite.cellIndex / rowSize) >> 0;
  52521. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  52522. this._vertexData[arrayOffset + 11] = offset;
  52523. // Color
  52524. this._vertexData[arrayOffset + 12] = sprite.color.r;
  52525. this._vertexData[arrayOffset + 13] = sprite.color.g;
  52526. this._vertexData[arrayOffset + 14] = sprite.color.b;
  52527. this._vertexData[arrayOffset + 15] = sprite.color.a;
  52528. };
  52529. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  52530. var count = Math.min(this._capacity, this.sprites.length);
  52531. var min = BABYLON.Vector3.Zero();
  52532. var max = BABYLON.Vector3.Zero();
  52533. var distance = Number.MAX_VALUE;
  52534. var currentSprite = null;
  52535. var cameraSpacePosition = BABYLON.Vector3.Zero();
  52536. var cameraView = camera.getViewMatrix();
  52537. for (var index = 0; index < count; index++) {
  52538. var sprite = this.sprites[index];
  52539. if (!sprite) {
  52540. continue;
  52541. }
  52542. if (predicate) {
  52543. if (!predicate(sprite)) {
  52544. continue;
  52545. }
  52546. }
  52547. else if (!sprite.isPickable) {
  52548. continue;
  52549. }
  52550. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  52551. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  52552. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  52553. if (ray.intersectsBoxMinMax(min, max)) {
  52554. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  52555. if (distance > currentDistance) {
  52556. distance = currentDistance;
  52557. currentSprite = sprite;
  52558. if (fastCheck) {
  52559. break;
  52560. }
  52561. }
  52562. }
  52563. }
  52564. if (currentSprite) {
  52565. var result = new BABYLON.PickingInfo();
  52566. result.hit = true;
  52567. result.pickedSprite = currentSprite;
  52568. result.distance = distance;
  52569. return result;
  52570. }
  52571. return null;
  52572. };
  52573. SpriteManager.prototype.render = function () {
  52574. // Check
  52575. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  52576. return;
  52577. var engine = this._scene.getEngine();
  52578. var baseSize = this._spriteTexture.getBaseSize();
  52579. // Sprites
  52580. var deltaTime = engine.getDeltaTime();
  52581. var max = Math.min(this._capacity, this.sprites.length);
  52582. var rowSize = baseSize.width / this.cellWidth;
  52583. var offset = 0;
  52584. for (var index = 0; index < max; index++) {
  52585. var sprite = this.sprites[index];
  52586. if (!sprite) {
  52587. continue;
  52588. }
  52589. sprite._animate(deltaTime);
  52590. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  52591. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  52592. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  52593. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  52594. }
  52595. this._buffer.update(this._vertexData);
  52596. // Render
  52597. var effect = this._effectBase;
  52598. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52599. effect = this._effectFog;
  52600. }
  52601. engine.enableEffect(effect);
  52602. var viewMatrix = this._scene.getViewMatrix();
  52603. effect.setTexture("diffuseSampler", this._spriteTexture);
  52604. effect.setMatrix("view", viewMatrix);
  52605. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52606. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  52607. // Fog
  52608. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52609. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  52610. effect.setColor3("vFogColor", this._scene.fogColor);
  52611. }
  52612. // VBOs
  52613. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52614. // Draw order
  52615. engine.setDepthFunctionToLessOrEqual();
  52616. effect.setBool("alphaTest", true);
  52617. engine.setColorWrite(false);
  52618. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52619. engine.setColorWrite(true);
  52620. effect.setBool("alphaTest", false);
  52621. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52622. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52623. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52624. };
  52625. SpriteManager.prototype.dispose = function () {
  52626. if (this._buffer) {
  52627. this._buffer.dispose();
  52628. this._buffer = null;
  52629. }
  52630. if (this._indexBuffer) {
  52631. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52632. this._indexBuffer = null;
  52633. }
  52634. if (this._spriteTexture) {
  52635. this._spriteTexture.dispose();
  52636. this._spriteTexture = null;
  52637. }
  52638. // Remove from scene
  52639. var index = this._scene.spriteManagers.indexOf(this);
  52640. this._scene.spriteManagers.splice(index, 1);
  52641. // Callback
  52642. this.onDisposeObservable.notifyObservers(this);
  52643. this.onDisposeObservable.clear();
  52644. };
  52645. return SpriteManager;
  52646. }());
  52647. BABYLON.SpriteManager = SpriteManager;
  52648. })(BABYLON || (BABYLON = {}));
  52649. //# sourceMappingURL=babylon.spriteManager.js.map
  52650. "use strict";
  52651. var BABYLON;
  52652. (function (BABYLON) {
  52653. var Sprite = /** @class */ (function () {
  52654. function Sprite(name, manager) {
  52655. this.name = name;
  52656. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52657. this.width = 1.0;
  52658. this.height = 1.0;
  52659. this.angle = 0;
  52660. this.cellIndex = 0;
  52661. this.invertU = 0;
  52662. this.invertV = 0;
  52663. this.animations = new Array();
  52664. this.isPickable = false;
  52665. this._animationStarted = false;
  52666. this._loopAnimation = false;
  52667. this._fromIndex = 0;
  52668. this._toIndex = 0;
  52669. this._delay = 0;
  52670. this._direction = 1;
  52671. this._time = 0;
  52672. this._manager = manager;
  52673. this._manager.sprites.push(this);
  52674. this.position = BABYLON.Vector3.Zero();
  52675. }
  52676. Object.defineProperty(Sprite.prototype, "size", {
  52677. get: function () {
  52678. return this.width;
  52679. },
  52680. set: function (value) {
  52681. this.width = value;
  52682. this.height = value;
  52683. },
  52684. enumerable: true,
  52685. configurable: true
  52686. });
  52687. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  52688. this._fromIndex = from;
  52689. this._toIndex = to;
  52690. this._loopAnimation = loop;
  52691. this._delay = delay;
  52692. this._animationStarted = true;
  52693. this._direction = from < to ? 1 : -1;
  52694. this.cellIndex = from;
  52695. this._time = 0;
  52696. this._onAnimationEnd = onAnimationEnd;
  52697. };
  52698. Sprite.prototype.stopAnimation = function () {
  52699. this._animationStarted = false;
  52700. };
  52701. Sprite.prototype._animate = function (deltaTime) {
  52702. if (!this._animationStarted)
  52703. return;
  52704. this._time += deltaTime;
  52705. if (this._time > this._delay) {
  52706. this._time = this._time % this._delay;
  52707. this.cellIndex += this._direction;
  52708. if (this.cellIndex > this._toIndex) {
  52709. if (this._loopAnimation) {
  52710. this.cellIndex = this._fromIndex;
  52711. }
  52712. else {
  52713. this.cellIndex = this._toIndex;
  52714. this._animationStarted = false;
  52715. if (this._onAnimationEnd) {
  52716. this._onAnimationEnd();
  52717. }
  52718. if (this.disposeWhenFinishedAnimating) {
  52719. this.dispose();
  52720. }
  52721. }
  52722. }
  52723. }
  52724. };
  52725. Sprite.prototype.dispose = function () {
  52726. for (var i = 0; i < this._manager.sprites.length; i++) {
  52727. if (this._manager.sprites[i] == this) {
  52728. this._manager.sprites.splice(i, 1);
  52729. }
  52730. }
  52731. };
  52732. return Sprite;
  52733. }());
  52734. BABYLON.Sprite = Sprite;
  52735. })(BABYLON || (BABYLON = {}));
  52736. //# sourceMappingURL=babylon.sprite.js.map
  52737. "use strict";
  52738. var BABYLON;
  52739. (function (BABYLON) {
  52740. var IntersectionInfo = /** @class */ (function () {
  52741. function IntersectionInfo(bu, bv, distance) {
  52742. this.bu = bu;
  52743. this.bv = bv;
  52744. this.distance = distance;
  52745. this.faceId = 0;
  52746. this.subMeshId = 0;
  52747. }
  52748. return IntersectionInfo;
  52749. }());
  52750. BABYLON.IntersectionInfo = IntersectionInfo;
  52751. var PickingInfo = /** @class */ (function () {
  52752. function PickingInfo() {
  52753. this.hit = false;
  52754. this.distance = 0;
  52755. this.pickedPoint = null;
  52756. this.pickedMesh = null;
  52757. this.bu = 0;
  52758. this.bv = 0;
  52759. this.faceId = -1;
  52760. this.subMeshId = 0;
  52761. this.pickedSprite = null;
  52762. }
  52763. // Methods
  52764. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  52765. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  52766. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  52767. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  52768. return null;
  52769. }
  52770. var indices = this.pickedMesh.getIndices();
  52771. if (!indices) {
  52772. return null;
  52773. }
  52774. var result;
  52775. if (useVerticesNormals) {
  52776. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52777. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  52778. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  52779. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  52780. normal0 = normal0.scale(this.bu);
  52781. normal1 = normal1.scale(this.bv);
  52782. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  52783. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  52784. }
  52785. else {
  52786. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52787. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  52788. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  52789. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  52790. var p1p2 = vertex1.subtract(vertex2);
  52791. var p3p2 = vertex3.subtract(vertex2);
  52792. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  52793. }
  52794. if (useWorldCoordinates) {
  52795. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  52796. }
  52797. return BABYLON.Vector3.Normalize(result);
  52798. };
  52799. PickingInfo.prototype.getTextureCoordinates = function () {
  52800. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52801. return null;
  52802. }
  52803. var indices = this.pickedMesh.getIndices();
  52804. if (!indices) {
  52805. return null;
  52806. }
  52807. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52808. if (!uvs) {
  52809. return null;
  52810. }
  52811. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  52812. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  52813. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  52814. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  52815. uv1 = uv1.scale(this.bu);
  52816. uv2 = uv2.scale(this.bv);
  52817. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  52818. };
  52819. return PickingInfo;
  52820. }());
  52821. BABYLON.PickingInfo = PickingInfo;
  52822. })(BABYLON || (BABYLON = {}));
  52823. //# sourceMappingURL=babylon.pickingInfo.js.map
  52824. "use strict";
  52825. var BABYLON;
  52826. (function (BABYLON) {
  52827. var Ray = /** @class */ (function () {
  52828. function Ray(origin, direction, length) {
  52829. if (length === void 0) { length = Number.MAX_VALUE; }
  52830. this.origin = origin;
  52831. this.direction = direction;
  52832. this.length = length;
  52833. }
  52834. // Methods
  52835. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  52836. var d = 0.0;
  52837. var maxValue = Number.MAX_VALUE;
  52838. var inv;
  52839. var min;
  52840. var max;
  52841. var temp;
  52842. if (Math.abs(this.direction.x) < 0.0000001) {
  52843. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  52844. return false;
  52845. }
  52846. }
  52847. else {
  52848. inv = 1.0 / this.direction.x;
  52849. min = (minimum.x - this.origin.x) * inv;
  52850. max = (maximum.x - this.origin.x) * inv;
  52851. if (max === -Infinity) {
  52852. max = Infinity;
  52853. }
  52854. if (min > max) {
  52855. temp = min;
  52856. min = max;
  52857. max = temp;
  52858. }
  52859. d = Math.max(min, d);
  52860. maxValue = Math.min(max, maxValue);
  52861. if (d > maxValue) {
  52862. return false;
  52863. }
  52864. }
  52865. if (Math.abs(this.direction.y) < 0.0000001) {
  52866. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  52867. return false;
  52868. }
  52869. }
  52870. else {
  52871. inv = 1.0 / this.direction.y;
  52872. min = (minimum.y - this.origin.y) * inv;
  52873. max = (maximum.y - this.origin.y) * inv;
  52874. if (max === -Infinity) {
  52875. max = Infinity;
  52876. }
  52877. if (min > max) {
  52878. temp = min;
  52879. min = max;
  52880. max = temp;
  52881. }
  52882. d = Math.max(min, d);
  52883. maxValue = Math.min(max, maxValue);
  52884. if (d > maxValue) {
  52885. return false;
  52886. }
  52887. }
  52888. if (Math.abs(this.direction.z) < 0.0000001) {
  52889. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  52890. return false;
  52891. }
  52892. }
  52893. else {
  52894. inv = 1.0 / this.direction.z;
  52895. min = (minimum.z - this.origin.z) * inv;
  52896. max = (maximum.z - this.origin.z) * inv;
  52897. if (max === -Infinity) {
  52898. max = Infinity;
  52899. }
  52900. if (min > max) {
  52901. temp = min;
  52902. min = max;
  52903. max = temp;
  52904. }
  52905. d = Math.max(min, d);
  52906. maxValue = Math.min(max, maxValue);
  52907. if (d > maxValue) {
  52908. return false;
  52909. }
  52910. }
  52911. return true;
  52912. };
  52913. Ray.prototype.intersectsBox = function (box) {
  52914. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  52915. };
  52916. Ray.prototype.intersectsSphere = function (sphere) {
  52917. var x = sphere.center.x - this.origin.x;
  52918. var y = sphere.center.y - this.origin.y;
  52919. var z = sphere.center.z - this.origin.z;
  52920. var pyth = (x * x) + (y * y) + (z * z);
  52921. var rr = sphere.radius * sphere.radius;
  52922. if (pyth <= rr) {
  52923. return true;
  52924. }
  52925. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  52926. if (dot < 0.0) {
  52927. return false;
  52928. }
  52929. var temp = pyth - (dot * dot);
  52930. return temp <= rr;
  52931. };
  52932. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  52933. if (!this._edge1) {
  52934. this._edge1 = BABYLON.Vector3.Zero();
  52935. this._edge2 = BABYLON.Vector3.Zero();
  52936. this._pvec = BABYLON.Vector3.Zero();
  52937. this._tvec = BABYLON.Vector3.Zero();
  52938. this._qvec = BABYLON.Vector3.Zero();
  52939. }
  52940. vertex1.subtractToRef(vertex0, this._edge1);
  52941. vertex2.subtractToRef(vertex0, this._edge2);
  52942. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  52943. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  52944. if (det === 0) {
  52945. return null;
  52946. }
  52947. var invdet = 1 / det;
  52948. this.origin.subtractToRef(vertex0, this._tvec);
  52949. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  52950. if (bu < 0 || bu > 1.0) {
  52951. return null;
  52952. }
  52953. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  52954. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  52955. if (bv < 0 || bu + bv > 1.0) {
  52956. return null;
  52957. }
  52958. //check if the distance is longer than the predefined length.
  52959. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  52960. if (distance > this.length) {
  52961. return null;
  52962. }
  52963. return new BABYLON.IntersectionInfo(bu, bv, distance);
  52964. };
  52965. Ray.prototype.intersectsPlane = function (plane) {
  52966. var distance;
  52967. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  52968. if (Math.abs(result1) < 9.99999997475243E-07) {
  52969. return null;
  52970. }
  52971. else {
  52972. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  52973. distance = (-plane.d - result2) / result1;
  52974. if (distance < 0.0) {
  52975. if (distance < -9.99999997475243E-07) {
  52976. return null;
  52977. }
  52978. else {
  52979. return 0;
  52980. }
  52981. }
  52982. return distance;
  52983. }
  52984. };
  52985. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  52986. var tm = BABYLON.Tmp.Matrix[0];
  52987. mesh.getWorldMatrix().invertToRef(tm);
  52988. if (this._tmpRay) {
  52989. Ray.TransformToRef(this, tm, this._tmpRay);
  52990. }
  52991. else {
  52992. this._tmpRay = Ray.Transform(this, tm);
  52993. }
  52994. return mesh.intersects(this._tmpRay, fastCheck);
  52995. };
  52996. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  52997. if (results) {
  52998. results.length = 0;
  52999. }
  53000. else {
  53001. results = [];
  53002. }
  53003. for (var i = 0; i < meshes.length; i++) {
  53004. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53005. if (pickInfo.hit) {
  53006. results.push(pickInfo);
  53007. }
  53008. }
  53009. results.sort(this._comparePickingInfo);
  53010. return results;
  53011. };
  53012. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53013. if (pickingInfoA.distance < pickingInfoB.distance) {
  53014. return -1;
  53015. }
  53016. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53017. return 1;
  53018. }
  53019. else {
  53020. return 0;
  53021. }
  53022. };
  53023. /**
  53024. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53025. * @param sega the first point of the segment to test the intersection against
  53026. * @param segb the second point of the segment to test the intersection against
  53027. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53028. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53029. */
  53030. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53031. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53032. var u = segb.subtract(sega);
  53033. var v = rsegb.subtract(this.origin);
  53034. var w = sega.subtract(this.origin);
  53035. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53036. var b = BABYLON.Vector3.Dot(u, v);
  53037. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53038. var d = BABYLON.Vector3.Dot(u, w);
  53039. var e = BABYLON.Vector3.Dot(v, w);
  53040. var D = a * c - b * b; // always >= 0
  53041. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53042. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53043. // compute the line parameters of the two closest points
  53044. if (D < Ray.smallnum) {
  53045. sN = 0.0; // force using point P0 on segment S1
  53046. sD = 1.0; // to prevent possible division by 0.0 later
  53047. tN = e;
  53048. tD = c;
  53049. }
  53050. else {
  53051. sN = (b * e - c * d);
  53052. tN = (a * e - b * d);
  53053. if (sN < 0.0) {
  53054. sN = 0.0;
  53055. tN = e;
  53056. tD = c;
  53057. }
  53058. else if (sN > sD) {
  53059. sN = sD;
  53060. tN = e + b;
  53061. tD = c;
  53062. }
  53063. }
  53064. if (tN < 0.0) {
  53065. tN = 0.0;
  53066. // recompute sc for this edge
  53067. if (-d < 0.0) {
  53068. sN = 0.0;
  53069. }
  53070. else if (-d > a)
  53071. sN = sD;
  53072. else {
  53073. sN = -d;
  53074. sD = a;
  53075. }
  53076. }
  53077. else if (tN > tD) {
  53078. tN = tD;
  53079. // recompute sc for this edge
  53080. if ((-d + b) < 0.0) {
  53081. sN = 0;
  53082. }
  53083. else if ((-d + b) > a) {
  53084. sN = sD;
  53085. }
  53086. else {
  53087. sN = (-d + b);
  53088. sD = a;
  53089. }
  53090. }
  53091. // finally do the division to get sc and tc
  53092. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53093. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53094. // get the difference of the two closest points
  53095. var qtc = v.multiplyByFloats(tc, tc, tc);
  53096. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53097. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53098. if (isIntersected) {
  53099. return qtc.length();
  53100. }
  53101. return -1;
  53102. };
  53103. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53104. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53105. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53106. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53107. this.direction.normalize();
  53108. return this;
  53109. };
  53110. // Statics
  53111. Ray.Zero = function () {
  53112. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53113. };
  53114. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53115. var result = Ray.Zero();
  53116. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53117. };
  53118. /**
  53119. * 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
  53120. * transformed to the given world matrix.
  53121. * @param origin The origin point
  53122. * @param end The end point
  53123. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53124. */
  53125. Ray.CreateNewFromTo = function (origin, end, world) {
  53126. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53127. var direction = end.subtract(origin);
  53128. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53129. direction.normalize();
  53130. return Ray.Transform(new Ray(origin, direction, length), world);
  53131. };
  53132. Ray.Transform = function (ray, matrix) {
  53133. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53134. Ray.TransformToRef(ray, matrix, result);
  53135. return result;
  53136. };
  53137. Ray.TransformToRef = function (ray, matrix, result) {
  53138. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53139. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53140. result.length = ray.length;
  53141. var dir = result.direction;
  53142. var len = dir.length();
  53143. if (!(len === 0 || len === 1)) {
  53144. var num = 1.0 / len;
  53145. dir.x *= num;
  53146. dir.y *= num;
  53147. dir.z *= num;
  53148. result.length *= len;
  53149. }
  53150. };
  53151. Ray.smallnum = 0.00000001;
  53152. Ray.rayl = 10e8;
  53153. return Ray;
  53154. }());
  53155. BABYLON.Ray = Ray;
  53156. })(BABYLON || (BABYLON = {}));
  53157. //# sourceMappingURL=babylon.ray.js.map
  53158. "use strict";
  53159. var BABYLON;
  53160. (function (BABYLON) {
  53161. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53162. if (boxMin.x > sphereCenter.x + sphereRadius)
  53163. return false;
  53164. if (sphereCenter.x - sphereRadius > boxMax.x)
  53165. return false;
  53166. if (boxMin.y > sphereCenter.y + sphereRadius)
  53167. return false;
  53168. if (sphereCenter.y - sphereRadius > boxMax.y)
  53169. return false;
  53170. if (boxMin.z > sphereCenter.z + sphereRadius)
  53171. return false;
  53172. if (sphereCenter.z - sphereRadius > boxMax.z)
  53173. return false;
  53174. return true;
  53175. };
  53176. var getLowestRoot = (function () {
  53177. var result = { root: 0, found: false };
  53178. return function (a, b, c, maxR) {
  53179. result.root = 0;
  53180. result.found = false;
  53181. var determinant = b * b - 4.0 * a * c;
  53182. if (determinant < 0)
  53183. return result;
  53184. var sqrtD = Math.sqrt(determinant);
  53185. var r1 = (-b - sqrtD) / (2.0 * a);
  53186. var r2 = (-b + sqrtD) / (2.0 * a);
  53187. if (r1 > r2) {
  53188. var temp = r2;
  53189. r2 = r1;
  53190. r1 = temp;
  53191. }
  53192. if (r1 > 0 && r1 < maxR) {
  53193. result.root = r1;
  53194. result.found = true;
  53195. return result;
  53196. }
  53197. if (r2 > 0 && r2 < maxR) {
  53198. result.root = r2;
  53199. result.found = true;
  53200. return result;
  53201. }
  53202. return result;
  53203. };
  53204. })();
  53205. var Collider = /** @class */ (function () {
  53206. function Collider() {
  53207. this._collisionPoint = BABYLON.Vector3.Zero();
  53208. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53209. this._tempVector = BABYLON.Vector3.Zero();
  53210. this._tempVector2 = BABYLON.Vector3.Zero();
  53211. this._tempVector3 = BABYLON.Vector3.Zero();
  53212. this._tempVector4 = BABYLON.Vector3.Zero();
  53213. this._edge = BABYLON.Vector3.Zero();
  53214. this._baseToVertex = BABYLON.Vector3.Zero();
  53215. this._destinationPoint = BABYLON.Vector3.Zero();
  53216. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53217. this._displacementVector = BABYLON.Vector3.Zero();
  53218. this._radius = BABYLON.Vector3.One();
  53219. this._retry = 0;
  53220. this._basePointWorld = BABYLON.Vector3.Zero();
  53221. this._velocityWorld = BABYLON.Vector3.Zero();
  53222. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53223. this._collisionMask = -1;
  53224. }
  53225. Object.defineProperty(Collider.prototype, "collisionMask", {
  53226. get: function () {
  53227. return this._collisionMask;
  53228. },
  53229. set: function (mask) {
  53230. this._collisionMask = !isNaN(mask) ? mask : -1;
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53236. /**
  53237. * Gets the plane normal used to compute the sliding response (in local space)
  53238. */
  53239. get: function () {
  53240. return this._slidePlaneNormal;
  53241. },
  53242. enumerable: true,
  53243. configurable: true
  53244. });
  53245. // Methods
  53246. Collider.prototype._initialize = function (source, dir, e) {
  53247. this._velocity = dir;
  53248. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53249. this._basePoint = source;
  53250. source.multiplyToRef(this._radius, this._basePointWorld);
  53251. dir.multiplyToRef(this._radius, this._velocityWorld);
  53252. this._velocityWorldLength = this._velocityWorld.length();
  53253. this._epsilon = e;
  53254. this.collisionFound = false;
  53255. };
  53256. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53257. pa.subtractToRef(point, this._tempVector);
  53258. pb.subtractToRef(point, this._tempVector2);
  53259. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53260. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53261. if (d < 0)
  53262. return false;
  53263. pc.subtractToRef(point, this._tempVector3);
  53264. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53265. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53266. if (d < 0)
  53267. return false;
  53268. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53269. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53270. return d >= 0;
  53271. };
  53272. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53273. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53274. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53275. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53276. return false;
  53277. }
  53278. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53279. return false;
  53280. return true;
  53281. };
  53282. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53283. var t0;
  53284. var embeddedInPlane = false;
  53285. //defensive programming, actually not needed.
  53286. if (!trianglePlaneArray) {
  53287. trianglePlaneArray = [];
  53288. }
  53289. if (!trianglePlaneArray[faceIndex]) {
  53290. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53291. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53292. }
  53293. var trianglePlane = trianglePlaneArray[faceIndex];
  53294. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53295. return;
  53296. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53297. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53298. if (normalDotVelocity == 0) {
  53299. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53300. return;
  53301. embeddedInPlane = true;
  53302. t0 = 0;
  53303. }
  53304. else {
  53305. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53306. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53307. if (t0 > t1) {
  53308. var temp = t1;
  53309. t1 = t0;
  53310. t0 = temp;
  53311. }
  53312. if (t0 > 1.0 || t1 < 0.0)
  53313. return;
  53314. if (t0 < 0)
  53315. t0 = 0;
  53316. if (t0 > 1.0)
  53317. t0 = 1.0;
  53318. }
  53319. this._collisionPoint.copyFromFloats(0, 0, 0);
  53320. var found = false;
  53321. var t = 1.0;
  53322. if (!embeddedInPlane) {
  53323. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53324. this._velocity.scaleToRef(t0, this._tempVector);
  53325. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53326. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53327. found = true;
  53328. t = t0;
  53329. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53330. }
  53331. }
  53332. if (!found) {
  53333. var velocitySquaredLength = this._velocity.lengthSquared();
  53334. var a = velocitySquaredLength;
  53335. this._basePoint.subtractToRef(p1, this._tempVector);
  53336. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53337. var c = this._tempVector.lengthSquared() - 1.0;
  53338. var lowestRoot = getLowestRoot(a, b, c, t);
  53339. if (lowestRoot.found) {
  53340. t = lowestRoot.root;
  53341. found = true;
  53342. this._collisionPoint.copyFrom(p1);
  53343. }
  53344. this._basePoint.subtractToRef(p2, this._tempVector);
  53345. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53346. c = this._tempVector.lengthSquared() - 1.0;
  53347. lowestRoot = getLowestRoot(a, b, c, t);
  53348. if (lowestRoot.found) {
  53349. t = lowestRoot.root;
  53350. found = true;
  53351. this._collisionPoint.copyFrom(p2);
  53352. }
  53353. this._basePoint.subtractToRef(p3, this._tempVector);
  53354. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53355. c = this._tempVector.lengthSquared() - 1.0;
  53356. lowestRoot = getLowestRoot(a, b, c, t);
  53357. if (lowestRoot.found) {
  53358. t = lowestRoot.root;
  53359. found = true;
  53360. this._collisionPoint.copyFrom(p3);
  53361. }
  53362. p2.subtractToRef(p1, this._edge);
  53363. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53364. var edgeSquaredLength = this._edge.lengthSquared();
  53365. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53366. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53367. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53368. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53369. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53370. lowestRoot = getLowestRoot(a, b, c, t);
  53371. if (lowestRoot.found) {
  53372. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53373. if (f >= 0.0 && f <= 1.0) {
  53374. t = lowestRoot.root;
  53375. found = true;
  53376. this._edge.scaleInPlace(f);
  53377. p1.addToRef(this._edge, this._collisionPoint);
  53378. }
  53379. }
  53380. p3.subtractToRef(p2, this._edge);
  53381. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53382. edgeSquaredLength = this._edge.lengthSquared();
  53383. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53384. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53385. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53386. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53387. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53388. lowestRoot = getLowestRoot(a, b, c, t);
  53389. if (lowestRoot.found) {
  53390. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53391. if (f >= 0.0 && f <= 1.0) {
  53392. t = lowestRoot.root;
  53393. found = true;
  53394. this._edge.scaleInPlace(f);
  53395. p2.addToRef(this._edge, this._collisionPoint);
  53396. }
  53397. }
  53398. p1.subtractToRef(p3, this._edge);
  53399. p3.subtractToRef(this._basePoint, this._baseToVertex);
  53400. edgeSquaredLength = this._edge.lengthSquared();
  53401. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53402. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53403. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53404. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53405. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53406. lowestRoot = getLowestRoot(a, b, c, t);
  53407. if (lowestRoot.found) {
  53408. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53409. if (f >= 0.0 && f <= 1.0) {
  53410. t = lowestRoot.root;
  53411. found = true;
  53412. this._edge.scaleInPlace(f);
  53413. p3.addToRef(this._edge, this._collisionPoint);
  53414. }
  53415. }
  53416. }
  53417. if (found) {
  53418. var distToCollision = t * this._velocity.length();
  53419. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  53420. if (!this.intersectionPoint) {
  53421. this.intersectionPoint = this._collisionPoint.clone();
  53422. }
  53423. else {
  53424. this.intersectionPoint.copyFrom(this._collisionPoint);
  53425. }
  53426. this._nearestDistance = distToCollision;
  53427. this.collisionFound = true;
  53428. }
  53429. }
  53430. };
  53431. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  53432. for (var i = indexStart; i < indexEnd; i += 3) {
  53433. var p1 = pts[indices[i] - decal];
  53434. var p2 = pts[indices[i + 1] - decal];
  53435. var p3 = pts[indices[i + 2] - decal];
  53436. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  53437. }
  53438. };
  53439. Collider.prototype._getResponse = function (pos, vel) {
  53440. pos.addToRef(vel, this._destinationPoint);
  53441. vel.scaleInPlace((this._nearestDistance / vel.length()));
  53442. this._basePoint.addToRef(vel, pos);
  53443. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  53444. this._slidePlaneNormal.normalize();
  53445. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  53446. pos.addInPlace(this._displacementVector);
  53447. this.intersectionPoint.addInPlace(this._displacementVector);
  53448. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  53449. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  53450. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  53451. };
  53452. return Collider;
  53453. }());
  53454. BABYLON.Collider = Collider;
  53455. })(BABYLON || (BABYLON = {}));
  53456. //# sourceMappingURL=babylon.collider.js.map
  53457. "use strict";
  53458. var BABYLON;
  53459. (function (BABYLON) {
  53460. //WebWorker code will be inserted to this variable.
  53461. BABYLON.CollisionWorker = "";
  53462. var WorkerTaskType;
  53463. (function (WorkerTaskType) {
  53464. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  53465. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  53466. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  53467. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  53468. var WorkerReplyType;
  53469. (function (WorkerReplyType) {
  53470. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  53471. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  53472. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  53473. var CollisionCoordinatorWorker = /** @class */ (function () {
  53474. function CollisionCoordinatorWorker() {
  53475. var _this = this;
  53476. this._scaledPosition = BABYLON.Vector3.Zero();
  53477. this._scaledVelocity = BABYLON.Vector3.Zero();
  53478. this.onMeshUpdated = function (transformNode) {
  53479. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  53480. };
  53481. this.onGeometryUpdated = function (geometry) {
  53482. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  53483. };
  53484. this._afterRender = function () {
  53485. if (!_this._init)
  53486. return;
  53487. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  53488. return;
  53489. }
  53490. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  53491. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  53492. if (_this._runningUpdated > 4) {
  53493. return;
  53494. }
  53495. ++_this._runningUpdated;
  53496. var payload = {
  53497. updatedMeshes: _this._addUpdateMeshesList,
  53498. updatedGeometries: _this._addUpdateGeometriesList,
  53499. removedGeometries: _this._toRemoveGeometryArray,
  53500. removedMeshes: _this._toRemoveMeshesArray
  53501. };
  53502. var message = {
  53503. payload: payload,
  53504. taskType: WorkerTaskType.UPDATE
  53505. };
  53506. var serializable = [];
  53507. for (var id in payload.updatedGeometries) {
  53508. if (payload.updatedGeometries.hasOwnProperty(id)) {
  53509. //prepare transferables
  53510. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  53511. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  53512. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  53513. }
  53514. }
  53515. _this._worker.postMessage(message, serializable);
  53516. _this._addUpdateMeshesList = {};
  53517. _this._addUpdateGeometriesList = {};
  53518. _this._toRemoveGeometryArray = [];
  53519. _this._toRemoveMeshesArray = [];
  53520. };
  53521. this._onMessageFromWorker = function (e) {
  53522. var returnData = e.data;
  53523. if (returnData.error != WorkerReplyType.SUCCESS) {
  53524. //TODO what errors can be returned from the worker?
  53525. BABYLON.Tools.Warn("error returned from worker!");
  53526. return;
  53527. }
  53528. switch (returnData.taskType) {
  53529. case WorkerTaskType.INIT:
  53530. _this._init = true;
  53531. //Update the worked with ALL of the scene's current state
  53532. _this._scene.meshes.forEach(function (mesh) {
  53533. _this.onMeshAdded(mesh);
  53534. });
  53535. _this._scene.getGeometries().forEach(function (geometry) {
  53536. _this.onGeometryAdded(geometry);
  53537. });
  53538. break;
  53539. case WorkerTaskType.UPDATE:
  53540. _this._runningUpdated--;
  53541. break;
  53542. case WorkerTaskType.COLLIDE:
  53543. var returnPayload = returnData.payload;
  53544. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  53545. return;
  53546. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  53547. if (callback) {
  53548. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  53549. if (mesh) {
  53550. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  53551. }
  53552. }
  53553. //cleanup
  53554. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  53555. break;
  53556. }
  53557. };
  53558. this._collisionsCallbackArray = [];
  53559. this._init = false;
  53560. this._runningUpdated = 0;
  53561. this._addUpdateMeshesList = {};
  53562. this._addUpdateGeometriesList = {};
  53563. this._toRemoveGeometryArray = [];
  53564. this._toRemoveMeshesArray = [];
  53565. }
  53566. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53567. if (!this._init)
  53568. return;
  53569. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  53570. return;
  53571. position.divideToRef(collider._radius, this._scaledPosition);
  53572. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53573. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  53574. var payload = {
  53575. collider: {
  53576. position: this._scaledPosition.asArray(),
  53577. velocity: this._scaledVelocity.asArray(),
  53578. radius: collider._radius.asArray()
  53579. },
  53580. collisionId: collisionIndex,
  53581. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  53582. maximumRetry: maximumRetry
  53583. };
  53584. var message = {
  53585. payload: payload,
  53586. taskType: WorkerTaskType.COLLIDE
  53587. };
  53588. this._worker.postMessage(message);
  53589. };
  53590. CollisionCoordinatorWorker.prototype.init = function (scene) {
  53591. this._scene = scene;
  53592. this._scene.registerAfterRender(this._afterRender);
  53593. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  53594. this._worker = new Worker(workerUrl);
  53595. this._worker.onmessage = this._onMessageFromWorker;
  53596. var message = {
  53597. payload: {},
  53598. taskType: WorkerTaskType.INIT
  53599. };
  53600. this._worker.postMessage(message);
  53601. };
  53602. CollisionCoordinatorWorker.prototype.destroy = function () {
  53603. this._scene.unregisterAfterRender(this._afterRender);
  53604. this._worker.terminate();
  53605. };
  53606. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  53607. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  53608. this.onMeshUpdated(mesh);
  53609. };
  53610. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  53611. this._toRemoveMeshesArray.push(mesh.uniqueId);
  53612. };
  53613. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  53614. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  53615. geometry.onGeometryUpdated = this.onGeometryUpdated;
  53616. this.onGeometryUpdated(geometry);
  53617. };
  53618. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  53619. this._toRemoveGeometryArray.push(geometry.id);
  53620. };
  53621. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  53622. var submeshes = [];
  53623. if (mesh.subMeshes) {
  53624. submeshes = mesh.subMeshes.map(function (sm, idx) {
  53625. var boundingInfo = sm.getBoundingInfo();
  53626. return {
  53627. position: idx,
  53628. verticesStart: sm.verticesStart,
  53629. verticesCount: sm.verticesCount,
  53630. indexStart: sm.indexStart,
  53631. indexCount: sm.indexCount,
  53632. hasMaterial: !!sm.getMaterial(),
  53633. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53634. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53635. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53636. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  53637. };
  53638. });
  53639. }
  53640. var geometryId = null;
  53641. if (mesh instanceof BABYLON.Mesh) {
  53642. var geometry = mesh.geometry;
  53643. geometryId = geometry ? geometry.id : null;
  53644. }
  53645. else if (mesh instanceof BABYLON.InstancedMesh) {
  53646. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  53647. geometryId = geometry ? geometry.id : null;
  53648. }
  53649. var boundingInfo = mesh.getBoundingInfo();
  53650. return {
  53651. uniqueId: mesh.uniqueId,
  53652. id: mesh.id,
  53653. name: mesh.name,
  53654. geometryId: geometryId,
  53655. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53656. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53657. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53658. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  53659. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  53660. subMeshes: submeshes,
  53661. checkCollisions: mesh.checkCollisions
  53662. };
  53663. };
  53664. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  53665. return {
  53666. id: geometry.id,
  53667. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  53668. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  53669. indices: new Uint32Array(geometry.getIndices() || []),
  53670. };
  53671. };
  53672. return CollisionCoordinatorWorker;
  53673. }());
  53674. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  53675. var CollisionCoordinatorLegacy = /** @class */ (function () {
  53676. function CollisionCoordinatorLegacy() {
  53677. this._scaledPosition = BABYLON.Vector3.Zero();
  53678. this._scaledVelocity = BABYLON.Vector3.Zero();
  53679. this._finalPosition = BABYLON.Vector3.Zero();
  53680. }
  53681. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53682. position.divideToRef(collider._radius, this._scaledPosition);
  53683. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53684. collider.collidedMesh = null;
  53685. collider._retry = 0;
  53686. collider._initialVelocity = this._scaledVelocity;
  53687. collider._initialPosition = this._scaledPosition;
  53688. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  53689. this._finalPosition.multiplyInPlace(collider._radius);
  53690. //run the callback
  53691. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  53692. };
  53693. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  53694. this._scene = scene;
  53695. };
  53696. CollisionCoordinatorLegacy.prototype.destroy = function () {
  53697. //Legacy need no destruction method.
  53698. };
  53699. //No update in legacy mode
  53700. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  53701. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  53702. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  53703. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  53704. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  53705. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  53706. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  53707. if (excludedMesh === void 0) { excludedMesh = null; }
  53708. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  53709. if (collider._retry >= maximumRetry) {
  53710. finalPosition.copyFrom(position);
  53711. return;
  53712. }
  53713. // Check if this is a mesh else camera or -1
  53714. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  53715. collider._initialize(position, velocity, closeDistance);
  53716. // Check all meshes
  53717. for (var index = 0; index < this._scene.meshes.length; index++) {
  53718. var mesh = this._scene.meshes[index];
  53719. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  53720. mesh._checkCollision(collider);
  53721. }
  53722. }
  53723. if (!collider.collisionFound) {
  53724. position.addToRef(velocity, finalPosition);
  53725. return;
  53726. }
  53727. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  53728. collider._getResponse(position, velocity);
  53729. }
  53730. if (velocity.length() <= closeDistance) {
  53731. finalPosition.copyFrom(position);
  53732. return;
  53733. }
  53734. collider._retry++;
  53735. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  53736. };
  53737. return CollisionCoordinatorLegacy;
  53738. }());
  53739. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  53740. })(BABYLON || (BABYLON = {}));
  53741. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  53742. "use strict";
  53743. var BABYLON;
  53744. (function (BABYLON) {
  53745. /**
  53746. * A particle represents one of the element emitted by a particle system.
  53747. * This is mainly define by its coordinates, direction, velocity and age.
  53748. */
  53749. var Particle = /** @class */ (function () {
  53750. /**
  53751. * Creates a new instance Particle
  53752. * @param particleSystem the particle system the particle belongs to
  53753. */
  53754. function Particle(
  53755. /**
  53756. * particleSystem the particle system the particle belongs to.
  53757. */
  53758. particleSystem) {
  53759. this.particleSystem = particleSystem;
  53760. /**
  53761. * The world position of the particle in the scene.
  53762. */
  53763. this.position = BABYLON.Vector3.Zero();
  53764. /**
  53765. * The world direction of the particle in the scene.
  53766. */
  53767. this.direction = BABYLON.Vector3.Zero();
  53768. /**
  53769. * The color of the particle.
  53770. */
  53771. this.color = new BABYLON.Color4(0, 0, 0, 0);
  53772. /**
  53773. * The color change of the particle per step.
  53774. */
  53775. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  53776. /**
  53777. * Defines how long will the life of the particle be.
  53778. */
  53779. this.lifeTime = 1.0;
  53780. /**
  53781. * The current age of the particle.
  53782. */
  53783. this.age = 0;
  53784. /**
  53785. * The current size of the particle.
  53786. */
  53787. this.size = 0;
  53788. /**
  53789. * The current angle of the particle.
  53790. */
  53791. this.angle = 0;
  53792. /**
  53793. * Defines how fast is the angle changing.
  53794. */
  53795. this.angularSpeed = 0;
  53796. /**
  53797. * Defines the cell index used by the particle to be rendered from a sprite.
  53798. */
  53799. this.cellIndex = 0;
  53800. this._currentFrameCounter = 0;
  53801. if (!this.particleSystem.isAnimationSheetEnabled) {
  53802. return;
  53803. }
  53804. this.updateCellInfoFromSystem();
  53805. }
  53806. Particle.prototype.updateCellInfoFromSystem = function () {
  53807. this.cellIndex = this.particleSystem.startSpriteCellID;
  53808. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  53809. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  53810. }
  53811. else {
  53812. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  53813. }
  53814. };
  53815. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  53816. // (ageOffset / scaledUpdateSpeed) / available cells
  53817. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  53818. this._currentFrameCounter += scaledUpdateSpeed;
  53819. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  53820. this._currentFrameCounter = 0;
  53821. this.cellIndex++;
  53822. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  53823. this.cellIndex = this.particleSystem.endSpriteCellID;
  53824. }
  53825. }
  53826. };
  53827. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  53828. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  53829. this.cellIndex++;
  53830. this._currentFrameCounter = 0;
  53831. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  53832. if (this.particleSystem.spriteCellLoop) {
  53833. this.cellIndex = this.particleSystem.startSpriteCellID;
  53834. }
  53835. else {
  53836. this.cellIndex = this.particleSystem.endSpriteCellID;
  53837. }
  53838. }
  53839. }
  53840. else {
  53841. this._currentFrameCounter++;
  53842. }
  53843. };
  53844. /**
  53845. * Copy the properties of particle to another one.
  53846. * @param other the particle to copy the information to.
  53847. */
  53848. Particle.prototype.copyTo = function (other) {
  53849. other.position.copyFrom(this.position);
  53850. other.direction.copyFrom(this.direction);
  53851. other.color.copyFrom(this.color);
  53852. other.colorStep.copyFrom(this.colorStep);
  53853. other.lifeTime = this.lifeTime;
  53854. other.age = this.age;
  53855. other.size = this.size;
  53856. other.angle = this.angle;
  53857. other.angularSpeed = this.angularSpeed;
  53858. other.particleSystem = this.particleSystem;
  53859. other.cellIndex = this.cellIndex;
  53860. };
  53861. return Particle;
  53862. }());
  53863. BABYLON.Particle = Particle;
  53864. })(BABYLON || (BABYLON = {}));
  53865. //# sourceMappingURL=babylon.particle.js.map
  53866. "use strict";
  53867. var BABYLON;
  53868. (function (BABYLON) {
  53869. /**
  53870. * This represents a particle system in Babylon.
  53871. * 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.
  53872. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  53873. * @example https://doc.babylonjs.com/babylon101/particles
  53874. */
  53875. var ParticleSystem = /** @class */ (function () {
  53876. /**
  53877. * Instantiates a particle system.
  53878. * 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.
  53879. * @param name The name of the particle system
  53880. * @param capacity The max number of particles alive at the same time
  53881. * @param scene The scene the particle system belongs to
  53882. * @param customEffect a custom effect used to change the way particles are rendered by default
  53883. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  53884. * @param epsilon Offset used to render the particles
  53885. */
  53886. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  53887. if (customEffect === void 0) { customEffect = null; }
  53888. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  53889. if (epsilon === void 0) { epsilon = 0.01; }
  53890. var _this = this;
  53891. /**
  53892. * List of animations used by the particle system.
  53893. */
  53894. this.animations = [];
  53895. /**
  53896. * The rendering group used by the Particle system to chose when to render.
  53897. */
  53898. this.renderingGroupId = 0;
  53899. /**
  53900. * The emitter represents the Mesh or position we are attaching the particle system to.
  53901. */
  53902. this.emitter = null;
  53903. /**
  53904. * The maximum number of particles to emit per frame
  53905. */
  53906. this.emitRate = 10;
  53907. /**
  53908. * If you want to launch only a few particles at once, that can be done, as well.
  53909. */
  53910. this.manualEmitCount = -1;
  53911. /**
  53912. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53913. */
  53914. this.updateSpeed = 0.01;
  53915. /**
  53916. * The amount of time the particle system is running (depends of the overall update speed).
  53917. */
  53918. this.targetStopDuration = 0;
  53919. /**
  53920. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  53921. */
  53922. this.disposeOnStop = false;
  53923. /**
  53924. * Minimum power of emitting particles.
  53925. */
  53926. this.minEmitPower = 1;
  53927. /**
  53928. * Maximum power of emitting particles.
  53929. */
  53930. this.maxEmitPower = 1;
  53931. /**
  53932. * Minimum life time of emitting particles.
  53933. */
  53934. this.minLifeTime = 1;
  53935. /**
  53936. * Maximum life time of emitting particles.
  53937. */
  53938. this.maxLifeTime = 1;
  53939. /**
  53940. * Minimum Size of emitting particles.
  53941. */
  53942. this.minSize = 1;
  53943. /**
  53944. * Maximum Size of emitting particles.
  53945. */
  53946. this.maxSize = 1;
  53947. /**
  53948. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  53949. */
  53950. this.minAngularSpeed = 0;
  53951. /**
  53952. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  53953. */
  53954. this.maxAngularSpeed = 0;
  53955. /**
  53956. * The layer mask we are rendering the particles through.
  53957. */
  53958. this.layerMask = 0x0FFFFFFF;
  53959. /**
  53960. * This can help using your own shader to render the particle system.
  53961. * The according effect will be created
  53962. */
  53963. this.customShader = null;
  53964. /**
  53965. * By default particle system starts as soon as they are created. This prevents the
  53966. * automatic start to happen and let you decide when to start emitting particles.
  53967. */
  53968. this.preventAutoStart = false;
  53969. /**
  53970. * Callback triggered when the particle animation is ending.
  53971. */
  53972. this.onAnimationEnd = null;
  53973. /**
  53974. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53975. */
  53976. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  53977. /**
  53978. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53979. * to override the particles.
  53980. */
  53981. this.forceDepthWrite = false;
  53982. /**
  53983. * You can use gravity if you want to give an orientation to your particles.
  53984. */
  53985. this.gravity = BABYLON.Vector3.Zero();
  53986. /**
  53987. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53988. */
  53989. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53990. /**
  53991. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53992. */
  53993. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53994. /**
  53995. * Color the particle will have at the end of its lifetime.
  53996. */
  53997. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  53998. /**
  53999. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54000. */
  54001. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54002. /**
  54003. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54004. */
  54005. this.spriteCellLoop = true;
  54006. /**
  54007. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54008. */
  54009. this.spriteCellChangeSpeed = 0;
  54010. /**
  54011. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54012. */
  54013. this.startSpriteCellID = 0;
  54014. /**
  54015. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54016. */
  54017. this.endSpriteCellID = 0;
  54018. /**
  54019. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54020. */
  54021. this.spriteCellWidth = 0;
  54022. /**
  54023. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54024. */
  54025. this.spriteCellHeight = 0;
  54026. /**
  54027. * An event triggered when the system is disposed.
  54028. */
  54029. this.onDisposeObservable = new BABYLON.Observable();
  54030. this._particles = new Array();
  54031. this._stockParticles = new Array();
  54032. this._newPartsExcess = 0;
  54033. this._vertexBuffers = {};
  54034. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54035. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54036. this._scaledDirection = BABYLON.Vector3.Zero();
  54037. this._scaledGravity = BABYLON.Vector3.Zero();
  54038. this._currentRenderId = -1;
  54039. this._started = false;
  54040. this._stopped = false;
  54041. this._actualFrame = 0;
  54042. this._vertexBufferSize = 11;
  54043. // start of sub system methods
  54044. /**
  54045. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54046. * Its lifetime will start back at 0.
  54047. */
  54048. this.recycleParticle = function (particle) {
  54049. var lastParticle = _this._particles.pop();
  54050. if (lastParticle !== particle) {
  54051. lastParticle.copyTo(particle);
  54052. }
  54053. _this._stockParticles.push(lastParticle);
  54054. };
  54055. this._createParticle = function () {
  54056. var particle;
  54057. if (_this._stockParticles.length !== 0) {
  54058. particle = _this._stockParticles.pop();
  54059. particle.age = 0;
  54060. particle.cellIndex = _this.startSpriteCellID;
  54061. }
  54062. else {
  54063. particle = new BABYLON.Particle(_this);
  54064. }
  54065. return particle;
  54066. };
  54067. this._emitFromParticle = function (particle) {
  54068. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54069. return;
  54070. }
  54071. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54072. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54073. subSystem._rootParticleSystem = _this;
  54074. _this.activeSubSystems.push(subSystem);
  54075. subSystem.start();
  54076. };
  54077. this._appendParticleVertexes = null;
  54078. this.id = name;
  54079. this.name = name;
  54080. this._capacity = capacity;
  54081. this._epsilon = epsilon;
  54082. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54083. if (isAnimationSheetEnabled) {
  54084. this._vertexBufferSize = 12;
  54085. }
  54086. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54087. this._customEffect = customEffect;
  54088. scene.particleSystems.push(this);
  54089. this._createIndexBuffer();
  54090. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54091. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54092. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54093. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54094. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54095. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54096. if (this._isAnimationSheetEnabled) {
  54097. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54098. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54099. }
  54100. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54101. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54102. this._vertexBuffers["options"] = options;
  54103. // Default emitter type
  54104. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54105. this.updateFunction = function (particles) {
  54106. for (var index = 0; index < particles.length; index++) {
  54107. var particle = particles[index];
  54108. particle.age += _this._scaledUpdateSpeed;
  54109. if (particle.age >= particle.lifeTime) {
  54110. _this._emitFromParticle(particle);
  54111. _this.recycleParticle(particle);
  54112. index--;
  54113. continue;
  54114. }
  54115. else {
  54116. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54117. particle.color.addInPlace(_this._scaledColorStep);
  54118. if (particle.color.a < 0)
  54119. particle.color.a = 0;
  54120. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54121. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54122. particle.position.addInPlace(_this._scaledDirection);
  54123. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54124. particle.direction.addInPlace(_this._scaledGravity);
  54125. if (_this._isAnimationSheetEnabled) {
  54126. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54127. }
  54128. }
  54129. }
  54130. };
  54131. }
  54132. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54133. /**
  54134. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54135. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54136. */
  54137. get: function () {
  54138. if (this.particleEmitterType.direction1) {
  54139. return this.particleEmitterType.direction1;
  54140. }
  54141. return BABYLON.Vector3.Zero();
  54142. },
  54143. set: function (value) {
  54144. if (this.particleEmitterType.direction1) {
  54145. this.particleEmitterType.direction1 = value;
  54146. }
  54147. },
  54148. enumerable: true,
  54149. configurable: true
  54150. });
  54151. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54152. /**
  54153. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54154. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54155. */
  54156. get: function () {
  54157. if (this.particleEmitterType.direction2) {
  54158. return this.particleEmitterType.direction2;
  54159. }
  54160. return BABYLON.Vector3.Zero();
  54161. },
  54162. set: function (value) {
  54163. if (this.particleEmitterType.direction2) {
  54164. this.particleEmitterType.direction2 = value;
  54165. }
  54166. },
  54167. enumerable: true,
  54168. configurable: true
  54169. });
  54170. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54171. /**
  54172. * 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.
  54173. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54174. */
  54175. get: function () {
  54176. if (this.particleEmitterType.minEmitBox) {
  54177. return this.particleEmitterType.minEmitBox;
  54178. }
  54179. return BABYLON.Vector3.Zero();
  54180. },
  54181. set: function (value) {
  54182. if (this.particleEmitterType.minEmitBox) {
  54183. this.particleEmitterType.minEmitBox = value;
  54184. }
  54185. },
  54186. enumerable: true,
  54187. configurable: true
  54188. });
  54189. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54190. /**
  54191. * 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.
  54192. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54193. */
  54194. get: function () {
  54195. if (this.particleEmitterType.maxEmitBox) {
  54196. return this.particleEmitterType.maxEmitBox;
  54197. }
  54198. return BABYLON.Vector3.Zero();
  54199. },
  54200. set: function (value) {
  54201. if (this.particleEmitterType.maxEmitBox) {
  54202. this.particleEmitterType.maxEmitBox = value;
  54203. }
  54204. },
  54205. enumerable: true,
  54206. configurable: true
  54207. });
  54208. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54209. /**
  54210. * Sets a callback that will be triggered when the system is disposed.
  54211. */
  54212. set: function (callback) {
  54213. if (this._onDisposeObserver) {
  54214. this.onDisposeObservable.remove(this._onDisposeObserver);
  54215. }
  54216. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54217. },
  54218. enumerable: true,
  54219. configurable: true
  54220. });
  54221. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54222. /**
  54223. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54224. */
  54225. get: function () {
  54226. return this._isAnimationSheetEnabled;
  54227. },
  54228. enumerable: true,
  54229. configurable: true
  54230. });
  54231. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54232. //end of Sub-emitter
  54233. /**
  54234. * Gets the current list of active particles
  54235. */
  54236. get: function () {
  54237. return this._particles;
  54238. },
  54239. enumerable: true,
  54240. configurable: true
  54241. });
  54242. /**
  54243. * Returns the string "ParticleSystem"
  54244. * @returns a string containing the class name
  54245. */
  54246. ParticleSystem.prototype.getClassName = function () {
  54247. return "ParticleSystem";
  54248. };
  54249. ParticleSystem.prototype._createIndexBuffer = function () {
  54250. var indices = [];
  54251. var index = 0;
  54252. for (var count = 0; count < this._capacity; count++) {
  54253. indices.push(index);
  54254. indices.push(index + 1);
  54255. indices.push(index + 2);
  54256. indices.push(index);
  54257. indices.push(index + 2);
  54258. indices.push(index + 3);
  54259. index += 4;
  54260. }
  54261. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54262. };
  54263. /**
  54264. * Gets the maximum number of particles active at the same time.
  54265. * @returns The max number of active particles.
  54266. */
  54267. ParticleSystem.prototype.getCapacity = function () {
  54268. return this._capacity;
  54269. };
  54270. /**
  54271. * Gets Wether there are still active particles in the system.
  54272. * @returns True if it is alive, otherwise false.
  54273. */
  54274. ParticleSystem.prototype.isAlive = function () {
  54275. return this._alive;
  54276. };
  54277. /**
  54278. * Gets Wether the system has been started.
  54279. * @returns True if it has been started, otherwise false.
  54280. */
  54281. ParticleSystem.prototype.isStarted = function () {
  54282. return this._started;
  54283. };
  54284. /**
  54285. * Starts the particle system and begins to emit.
  54286. */
  54287. ParticleSystem.prototype.start = function () {
  54288. this._started = true;
  54289. this._stopped = false;
  54290. this._actualFrame = 0;
  54291. if (this.subEmitters && this.subEmitters.length != 0) {
  54292. this.activeSubSystems = new Array();
  54293. }
  54294. };
  54295. /**
  54296. * Stops the particle system.
  54297. * @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.
  54298. */
  54299. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54300. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54301. this._stopped = true;
  54302. if (stopSubEmitters) {
  54303. this._stopSubEmitters();
  54304. }
  54305. };
  54306. // animation sheet
  54307. /**
  54308. * Remove all active particles
  54309. */
  54310. ParticleSystem.prototype.reset = function () {
  54311. this._stockParticles = [];
  54312. this._particles = [];
  54313. };
  54314. /**
  54315. * @ignore (for internal use only)
  54316. */
  54317. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54318. var offset = index * this._vertexBufferSize;
  54319. this._vertexData[offset] = particle.position.x;
  54320. this._vertexData[offset + 1] = particle.position.y;
  54321. this._vertexData[offset + 2] = particle.position.z;
  54322. this._vertexData[offset + 3] = particle.color.r;
  54323. this._vertexData[offset + 4] = particle.color.g;
  54324. this._vertexData[offset + 5] = particle.color.b;
  54325. this._vertexData[offset + 6] = particle.color.a;
  54326. this._vertexData[offset + 7] = particle.angle;
  54327. this._vertexData[offset + 8] = particle.size;
  54328. this._vertexData[offset + 9] = offsetX;
  54329. this._vertexData[offset + 10] = offsetY;
  54330. };
  54331. /**
  54332. * @ignore (for internal use only)
  54333. */
  54334. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54335. if (offsetX === 0)
  54336. offsetX = this._epsilon;
  54337. else if (offsetX === 1)
  54338. offsetX = 1 - this._epsilon;
  54339. if (offsetY === 0)
  54340. offsetY = this._epsilon;
  54341. else if (offsetY === 1)
  54342. offsetY = 1 - this._epsilon;
  54343. var offset = index * this._vertexBufferSize;
  54344. this._vertexData[offset] = particle.position.x;
  54345. this._vertexData[offset + 1] = particle.position.y;
  54346. this._vertexData[offset + 2] = particle.position.z;
  54347. this._vertexData[offset + 3] = particle.color.r;
  54348. this._vertexData[offset + 4] = particle.color.g;
  54349. this._vertexData[offset + 5] = particle.color.b;
  54350. this._vertexData[offset + 6] = particle.color.a;
  54351. this._vertexData[offset + 7] = particle.angle;
  54352. this._vertexData[offset + 8] = particle.size;
  54353. this._vertexData[offset + 9] = offsetX;
  54354. this._vertexData[offset + 10] = offsetY;
  54355. this._vertexData[offset + 11] = particle.cellIndex;
  54356. };
  54357. ParticleSystem.prototype._stopSubEmitters = function () {
  54358. if (!this.activeSubSystems) {
  54359. return;
  54360. }
  54361. this.activeSubSystems.forEach(function (subSystem) {
  54362. subSystem.stop(true);
  54363. });
  54364. this.activeSubSystems = new Array();
  54365. };
  54366. ParticleSystem.prototype._removeFromRoot = function () {
  54367. if (!this._rootParticleSystem) {
  54368. return;
  54369. }
  54370. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54371. if (index !== -1) {
  54372. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54373. }
  54374. };
  54375. // end of sub system methods
  54376. ParticleSystem.prototype._update = function (newParticles) {
  54377. // Update current
  54378. this._alive = this._particles.length > 0;
  54379. this.updateFunction(this._particles);
  54380. // Add new ones
  54381. var worldMatrix;
  54382. if (this.emitter.position) {
  54383. var emitterMesh = this.emitter;
  54384. worldMatrix = emitterMesh.getWorldMatrix();
  54385. }
  54386. else {
  54387. var emitterPosition = this.emitter;
  54388. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54389. }
  54390. var particle;
  54391. for (var index = 0; index < newParticles; index++) {
  54392. if (this._particles.length === this._capacity) {
  54393. break;
  54394. }
  54395. particle = this._createParticle();
  54396. this._particles.push(particle);
  54397. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  54398. if (this.startPositionFunction) {
  54399. this.startPositionFunction(worldMatrix, particle.position, particle);
  54400. }
  54401. else {
  54402. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  54403. }
  54404. if (this.startDirectionFunction) {
  54405. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54406. }
  54407. else {
  54408. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54409. }
  54410. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  54411. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  54412. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  54413. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  54414. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  54415. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  54416. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  54417. }
  54418. };
  54419. ParticleSystem.prototype._getEffect = function () {
  54420. if (this._customEffect) {
  54421. return this._customEffect;
  54422. }
  54423. ;
  54424. var defines = [];
  54425. if (this._scene.clipPlane) {
  54426. defines.push("#define CLIPPLANE");
  54427. }
  54428. if (this._isAnimationSheetEnabled) {
  54429. defines.push("#define ANIMATESHEET");
  54430. }
  54431. // Effect
  54432. var join = defines.join("\n");
  54433. if (this._cachedDefines !== join) {
  54434. this._cachedDefines = join;
  54435. var attributesNamesOrOptions;
  54436. var effectCreationOption;
  54437. if (this._isAnimationSheetEnabled) {
  54438. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  54439. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  54440. }
  54441. else {
  54442. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  54443. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  54444. }
  54445. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  54446. }
  54447. return this._effect;
  54448. };
  54449. /**
  54450. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54451. */
  54452. ParticleSystem.prototype.animate = function () {
  54453. if (!this._started)
  54454. return;
  54455. var effect = this._getEffect();
  54456. // Check
  54457. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  54458. return;
  54459. if (this._currentRenderId === this._scene.getRenderId()) {
  54460. return;
  54461. }
  54462. this._currentRenderId = this._scene.getRenderId();
  54463. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  54464. // determine the number of particles we need to create
  54465. var newParticles;
  54466. if (this.manualEmitCount > -1) {
  54467. newParticles = this.manualEmitCount;
  54468. this._newPartsExcess = 0;
  54469. this.manualEmitCount = 0;
  54470. }
  54471. else {
  54472. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  54473. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  54474. }
  54475. if (this._newPartsExcess > 1.0) {
  54476. newParticles += this._newPartsExcess >> 0;
  54477. this._newPartsExcess -= this._newPartsExcess >> 0;
  54478. }
  54479. this._alive = false;
  54480. if (!this._stopped) {
  54481. this._actualFrame += this._scaledUpdateSpeed;
  54482. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  54483. this.stop();
  54484. }
  54485. else {
  54486. newParticles = 0;
  54487. }
  54488. this._update(newParticles);
  54489. // Stopped?
  54490. if (this._stopped) {
  54491. if (!this._alive) {
  54492. this._started = false;
  54493. if (this.onAnimationEnd) {
  54494. this.onAnimationEnd();
  54495. }
  54496. if (this.disposeOnStop) {
  54497. this._scene._toBeDisposed.push(this);
  54498. }
  54499. }
  54500. }
  54501. // Animation sheet
  54502. if (this._isAnimationSheetEnabled) {
  54503. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  54504. }
  54505. else {
  54506. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  54507. }
  54508. // Update VBO
  54509. var offset = 0;
  54510. for (var index = 0; index < this._particles.length; index++) {
  54511. var particle = this._particles[index];
  54512. this._appendParticleVertexes(offset, particle);
  54513. offset += 4;
  54514. }
  54515. if (this._vertexBuffer) {
  54516. this._vertexBuffer.update(this._vertexData);
  54517. }
  54518. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  54519. this.stop();
  54520. }
  54521. };
  54522. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  54523. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  54524. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  54525. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  54526. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  54527. };
  54528. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  54529. this._appendParticleVertex(offset++, particle, 0, 0);
  54530. this._appendParticleVertex(offset++, particle, 1, 0);
  54531. this._appendParticleVertex(offset++, particle, 1, 1);
  54532. this._appendParticleVertex(offset++, particle, 0, 1);
  54533. };
  54534. /**
  54535. * Rebuilds the particle system.
  54536. */
  54537. ParticleSystem.prototype.rebuild = function () {
  54538. this._createIndexBuffer();
  54539. if (this._vertexBuffer) {
  54540. this._vertexBuffer._rebuild();
  54541. }
  54542. };
  54543. /**
  54544. * Is this system ready to be used/rendered
  54545. * @return true if the system is ready
  54546. */
  54547. ParticleSystem.prototype.isReady = function () {
  54548. var effect = this._getEffect();
  54549. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54550. return false;
  54551. }
  54552. return true;
  54553. };
  54554. /**
  54555. * Renders the particle system in its current state.
  54556. * @returns the current number of particles
  54557. */
  54558. ParticleSystem.prototype.render = function () {
  54559. var effect = this._getEffect();
  54560. // Check
  54561. if (!this.isReady() || !this._particles.length) {
  54562. return 0;
  54563. }
  54564. var engine = this._scene.getEngine();
  54565. // Render
  54566. engine.enableEffect(effect);
  54567. engine.setState(false);
  54568. var viewMatrix = this._scene.getViewMatrix();
  54569. effect.setTexture("diffuseSampler", this.particleTexture);
  54570. effect.setMatrix("view", viewMatrix);
  54571. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54572. if (this._isAnimationSheetEnabled && this.particleTexture) {
  54573. var baseSize = this.particleTexture.getBaseSize();
  54574. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  54575. }
  54576. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  54577. if (this._scene.clipPlane) {
  54578. var clipPlane = this._scene.clipPlane;
  54579. var invView = viewMatrix.clone();
  54580. invView.invert();
  54581. effect.setMatrix("invView", invView);
  54582. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54583. }
  54584. // VBOs
  54585. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54586. // Draw order
  54587. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  54588. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54589. }
  54590. else {
  54591. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54592. }
  54593. if (this.forceDepthWrite) {
  54594. engine.setDepthWrite(true);
  54595. }
  54596. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  54597. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54598. return this._particles.length;
  54599. };
  54600. /**
  54601. * Disposes the particle system and free the associated resources
  54602. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54603. */
  54604. ParticleSystem.prototype.dispose = function (disposeTexture) {
  54605. if (disposeTexture === void 0) { disposeTexture = true; }
  54606. if (this._vertexBuffer) {
  54607. this._vertexBuffer.dispose();
  54608. this._vertexBuffer = null;
  54609. }
  54610. if (this._indexBuffer) {
  54611. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54612. this._indexBuffer = null;
  54613. }
  54614. if (disposeTexture && this.particleTexture) {
  54615. this.particleTexture.dispose();
  54616. this.particleTexture = null;
  54617. }
  54618. this._removeFromRoot();
  54619. // Remove from scene
  54620. var index = this._scene.particleSystems.indexOf(this);
  54621. if (index > -1) {
  54622. this._scene.particleSystems.splice(index, 1);
  54623. }
  54624. // Callback
  54625. this.onDisposeObservable.notifyObservers(this);
  54626. this.onDisposeObservable.clear();
  54627. };
  54628. /**
  54629. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  54630. * @param radius The radius of the sphere to emit from
  54631. * @returns the emitter
  54632. */
  54633. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  54634. if (radius === void 0) { radius = 1; }
  54635. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  54636. this.particleEmitterType = particleEmitter;
  54637. return particleEmitter;
  54638. };
  54639. /**
  54640. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  54641. * @param radius The radius of the sphere to emit from
  54642. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  54643. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  54644. * @returns the emitter
  54645. */
  54646. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  54647. if (radius === void 0) { radius = 1; }
  54648. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  54649. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  54650. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  54651. this.particleEmitterType = particleEmitter;
  54652. return particleEmitter;
  54653. };
  54654. /**
  54655. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  54656. * @param radius The radius of the cone to emit from
  54657. * @param angle The base angle of the cone
  54658. * @returns the emitter
  54659. */
  54660. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  54661. if (radius === void 0) { radius = 1; }
  54662. if (angle === void 0) { angle = Math.PI / 4; }
  54663. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  54664. this.particleEmitterType = particleEmitter;
  54665. return particleEmitter;
  54666. };
  54667. // 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.
  54668. /**
  54669. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  54670. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  54671. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  54672. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54673. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54674. * @returns the emitter
  54675. */
  54676. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  54677. var particleEmitter = new BABYLON.BoxParticleEmitter();
  54678. this.particleEmitterType = particleEmitter;
  54679. this.direction1 = direction1;
  54680. this.direction2 = direction2;
  54681. this.minEmitBox = minEmitBox;
  54682. this.maxEmitBox = maxEmitBox;
  54683. return particleEmitter;
  54684. };
  54685. // Clone
  54686. /**
  54687. * Clones the particle system.
  54688. * @param name The name of the cloned object
  54689. * @param newEmitter The new emitter to use
  54690. * @returns the cloned particle system
  54691. */
  54692. ParticleSystem.prototype.clone = function (name, newEmitter) {
  54693. var custom = null;
  54694. var program = null;
  54695. if (this.customShader != null) {
  54696. program = this.customShader;
  54697. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54698. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54699. }
  54700. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  54701. result.customShader = program;
  54702. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  54703. if (newEmitter === undefined) {
  54704. newEmitter = this.emitter;
  54705. }
  54706. result.emitter = newEmitter;
  54707. if (this.particleTexture) {
  54708. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  54709. }
  54710. if (!this.preventAutoStart) {
  54711. result.start();
  54712. }
  54713. return result;
  54714. };
  54715. /**
  54716. * Serializes the particle system to a JSON object.
  54717. * @returns the JSON object
  54718. */
  54719. ParticleSystem.prototype.serialize = function () {
  54720. var serializationObject = {};
  54721. serializationObject.name = this.name;
  54722. serializationObject.id = this.id;
  54723. // Emitter
  54724. if (this.emitter.position) {
  54725. var emitterMesh = this.emitter;
  54726. serializationObject.emitterId = emitterMesh.id;
  54727. }
  54728. else {
  54729. var emitterPosition = this.emitter;
  54730. serializationObject.emitter = emitterPosition.asArray();
  54731. }
  54732. serializationObject.capacity = this.getCapacity();
  54733. if (this.particleTexture) {
  54734. serializationObject.textureName = this.particleTexture.name;
  54735. }
  54736. // Animations
  54737. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  54738. // Particle system
  54739. serializationObject.minAngularSpeed = this.minAngularSpeed;
  54740. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  54741. serializationObject.minSize = this.minSize;
  54742. serializationObject.maxSize = this.maxSize;
  54743. serializationObject.minEmitPower = this.minEmitPower;
  54744. serializationObject.maxEmitPower = this.maxEmitPower;
  54745. serializationObject.minLifeTime = this.minLifeTime;
  54746. serializationObject.maxLifeTime = this.maxLifeTime;
  54747. serializationObject.emitRate = this.emitRate;
  54748. serializationObject.minEmitBox = this.minEmitBox.asArray();
  54749. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  54750. serializationObject.gravity = this.gravity.asArray();
  54751. serializationObject.direction1 = this.direction1.asArray();
  54752. serializationObject.direction2 = this.direction2.asArray();
  54753. serializationObject.color1 = this.color1.asArray();
  54754. serializationObject.color2 = this.color2.asArray();
  54755. serializationObject.colorDead = this.colorDead.asArray();
  54756. serializationObject.updateSpeed = this.updateSpeed;
  54757. serializationObject.targetStopDuration = this.targetStopDuration;
  54758. serializationObject.textureMask = this.textureMask.asArray();
  54759. serializationObject.blendMode = this.blendMode;
  54760. serializationObject.customShader = this.customShader;
  54761. serializationObject.preventAutoStart = this.preventAutoStart;
  54762. serializationObject.startSpriteCellID = this.startSpriteCellID;
  54763. serializationObject.endSpriteCellID = this.endSpriteCellID;
  54764. serializationObject.spriteCellLoop = this.spriteCellLoop;
  54765. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  54766. serializationObject.spriteCellWidth = this.spriteCellWidth;
  54767. serializationObject.spriteCellHeight = this.spriteCellHeight;
  54768. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  54769. // Emitter
  54770. if (this.particleEmitterType) {
  54771. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  54772. }
  54773. return serializationObject;
  54774. };
  54775. /**
  54776. * Parses a JSON object to create a particle system.
  54777. * @param parsedParticleSystem The JSON object to parse
  54778. * @param scene The scene to create the particle system in
  54779. * @param rootUrl The root url to use to load external dependencies like texture
  54780. * @returns the Parsed particle system
  54781. */
  54782. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  54783. var name = parsedParticleSystem.name;
  54784. var custom = null;
  54785. var program = null;
  54786. if (parsedParticleSystem.customShader) {
  54787. program = parsedParticleSystem.customShader;
  54788. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54789. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54790. }
  54791. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  54792. particleSystem.customShader = program;
  54793. if (parsedParticleSystem.id) {
  54794. particleSystem.id = parsedParticleSystem.id;
  54795. }
  54796. // Auto start
  54797. if (parsedParticleSystem.preventAutoStart) {
  54798. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  54799. }
  54800. // Texture
  54801. if (parsedParticleSystem.textureName) {
  54802. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  54803. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  54804. }
  54805. // Emitter
  54806. if (parsedParticleSystem.emitterId) {
  54807. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  54808. }
  54809. else {
  54810. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  54811. }
  54812. // Animations
  54813. if (parsedParticleSystem.animations) {
  54814. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  54815. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  54816. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54817. }
  54818. }
  54819. if (parsedParticleSystem.autoAnimate) {
  54820. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  54821. }
  54822. // Particle system
  54823. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  54824. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  54825. particleSystem.minSize = parsedParticleSystem.minSize;
  54826. particleSystem.maxSize = parsedParticleSystem.maxSize;
  54827. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  54828. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  54829. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  54830. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  54831. particleSystem.emitRate = parsedParticleSystem.emitRate;
  54832. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  54833. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  54834. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  54835. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  54836. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  54837. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  54838. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  54839. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  54840. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  54841. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  54842. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  54843. particleSystem.blendMode = parsedParticleSystem.blendMode;
  54844. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  54845. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  54846. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  54847. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  54848. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  54849. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  54850. if (!particleSystem.preventAutoStart) {
  54851. particleSystem.start();
  54852. }
  54853. return particleSystem;
  54854. };
  54855. /**
  54856. * Source color is added to the destination color without alpha affecting the result.
  54857. */
  54858. ParticleSystem.BLENDMODE_ONEONE = 0;
  54859. /**
  54860. * Blend current color and particle color using particle’s alpha.
  54861. */
  54862. ParticleSystem.BLENDMODE_STANDARD = 1;
  54863. return ParticleSystem;
  54864. }());
  54865. BABYLON.ParticleSystem = ParticleSystem;
  54866. })(BABYLON || (BABYLON = {}));
  54867. //# sourceMappingURL=babylon.particleSystem.js.map
  54868. "use strict";
  54869. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  54870. "use strict";
  54871. var BABYLON;
  54872. (function (BABYLON) {
  54873. /**
  54874. * Particle emitter emitting particles from the inside of a box.
  54875. * It emits the particles randomly between 2 given directions.
  54876. */
  54877. var BoxParticleEmitter = /** @class */ (function () {
  54878. /**
  54879. * Creates a new instance BoxParticleEmitter
  54880. */
  54881. function BoxParticleEmitter() {
  54882. /**
  54883. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54884. */
  54885. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  54886. /**
  54887. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54888. */
  54889. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  54890. /**
  54891. * 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.
  54892. */
  54893. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  54894. /**
  54895. * 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.
  54896. */
  54897. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  54898. }
  54899. /**
  54900. * Called by the particle System when the direction is computed for the created particle.
  54901. * @param emitPower is the power of the particle (speed)
  54902. * @param worldMatrix is the world matrix of the particle system
  54903. * @param directionToUpdate is the direction vector to update with the result
  54904. * @param particle is the particle we are computed the direction for
  54905. */
  54906. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  54907. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  54908. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  54909. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  54910. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  54911. };
  54912. /**
  54913. * Called by the particle System when the position is computed for the created particle.
  54914. * @param worldMatrix is the world matrix of the particle system
  54915. * @param positionToUpdate is the position vector to update with the result
  54916. * @param particle is the particle we are computed the position for
  54917. */
  54918. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  54919. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  54920. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  54921. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  54922. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  54923. };
  54924. /**
  54925. * Clones the current emitter and returns a copy of it
  54926. * @returns the new emitter
  54927. */
  54928. BoxParticleEmitter.prototype.clone = function () {
  54929. var newOne = new BoxParticleEmitter();
  54930. BABYLON.Tools.DeepCopy(this, newOne);
  54931. return newOne;
  54932. };
  54933. /**
  54934. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  54935. * @param effect defines the update shader
  54936. */
  54937. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  54938. effect.setVector3("direction1", this.direction1);
  54939. effect.setVector3("direction2", this.direction2);
  54940. effect.setVector3("minEmitBox", this.minEmitBox);
  54941. effect.setVector3("maxEmitBox", this.maxEmitBox);
  54942. };
  54943. /**
  54944. * Returns a string to use to update the GPU particles update shader
  54945. * @returns a string containng the defines string
  54946. */
  54947. BoxParticleEmitter.prototype.getEffectDefines = function () {
  54948. return "#define BOXEMITTER";
  54949. };
  54950. /**
  54951. * Returns the string "BoxEmitter"
  54952. * @returns a string containing the class name
  54953. */
  54954. BoxParticleEmitter.prototype.getClassName = function () {
  54955. return "BoxEmitter";
  54956. };
  54957. /**
  54958. * Serializes the particle system to a JSON object.
  54959. * @returns the JSON object
  54960. */
  54961. BoxParticleEmitter.prototype.serialize = function () {
  54962. var serializationObject = {};
  54963. serializationObject.type = this.getClassName();
  54964. serializationObject.direction1 = this.direction1.asArray();
  54965. ;
  54966. serializationObject.direction2 = this.direction2.asArray();
  54967. ;
  54968. serializationObject.minEmitBox = this.minEmitBox.asArray();
  54969. ;
  54970. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  54971. ;
  54972. return serializationObject;
  54973. };
  54974. /**
  54975. * Parse properties from a JSON object
  54976. * @param serializationObject defines the JSON object
  54977. */
  54978. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  54979. this.direction1.copyFrom(serializationObject.direction1);
  54980. this.direction2.copyFrom(serializationObject.direction2);
  54981. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  54982. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  54983. };
  54984. return BoxParticleEmitter;
  54985. }());
  54986. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  54987. })(BABYLON || (BABYLON = {}));
  54988. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  54989. "use strict";
  54990. var BABYLON;
  54991. (function (BABYLON) {
  54992. /**
  54993. * Particle emitter emitting particles from the inside of a cone.
  54994. * It emits the particles alongside the cone volume from the base to the particle.
  54995. * The emission direction might be randomized.
  54996. */
  54997. var ConeParticleEmitter = /** @class */ (function () {
  54998. /**
  54999. * Creates a new instance ConeParticleEmitter
  55000. * @param radius the radius of the emission cone (1 by default)
  55001. * @param angles the cone base angle (PI by default)
  55002. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55003. */
  55004. function ConeParticleEmitter(radius,
  55005. /**
  55006. * The radius of the emission cone.
  55007. */
  55008. angle,
  55009. /**
  55010. * The cone base angle.
  55011. */
  55012. directionRandomizer) {
  55013. if (radius === void 0) { radius = 1; }
  55014. if (angle === void 0) { angle = Math.PI; }
  55015. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55016. this.angle = angle;
  55017. this.directionRandomizer = directionRandomizer;
  55018. this.radius = radius;
  55019. }
  55020. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55021. /**
  55022. * Gets the radius of the emission cone.
  55023. */
  55024. get: function () {
  55025. return this._radius;
  55026. },
  55027. /**
  55028. * Sets the radius of the emission cone.
  55029. */
  55030. set: function (value) {
  55031. this._radius = value;
  55032. if (this.angle !== 0) {
  55033. this._height = value / Math.tan(this.angle / 2);
  55034. }
  55035. else {
  55036. this._height = 1;
  55037. }
  55038. },
  55039. enumerable: true,
  55040. configurable: true
  55041. });
  55042. /**
  55043. * Called by the particle System when the direction is computed for the created particle.
  55044. * @param emitPower is the power of the particle (speed)
  55045. * @param worldMatrix is the world matrix of the particle system
  55046. * @param directionToUpdate is the direction vector to update with the result
  55047. * @param particle is the particle we are computed the direction for
  55048. */
  55049. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55050. if (this.angle === 0) {
  55051. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55052. }
  55053. else {
  55054. // measure the direction Vector from the emitter to the particle.
  55055. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55056. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55057. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55058. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55059. direction.x += randX;
  55060. direction.y += randY;
  55061. direction.z += randZ;
  55062. direction.normalize();
  55063. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55064. }
  55065. };
  55066. /**
  55067. * Called by the particle System when the position is computed for the created particle.
  55068. * @param worldMatrix is the world matrix of the particle system
  55069. * @param positionToUpdate is the position vector to update with the result
  55070. * @param particle is the particle we are computed the position for
  55071. */
  55072. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55073. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55074. var h = BABYLON.Scalar.RandomRange(0, 1);
  55075. // Better distribution in a cone at normal angles.
  55076. h = 1 - h * h;
  55077. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55078. radius = radius * h;
  55079. var randX = radius * Math.sin(s);
  55080. var randZ = radius * Math.cos(s);
  55081. var randY = h * this._height;
  55082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55083. };
  55084. /**
  55085. * Clones the current emitter and returns a copy of it
  55086. * @returns the new emitter
  55087. */
  55088. ConeParticleEmitter.prototype.clone = function () {
  55089. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55090. BABYLON.Tools.DeepCopy(this, newOne);
  55091. return newOne;
  55092. };
  55093. /**
  55094. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55095. * @param effect defines the update shader
  55096. */
  55097. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55098. effect.setFloat("radius", this.radius);
  55099. effect.setFloat("angle", this.angle);
  55100. effect.setFloat("height", this._height);
  55101. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55102. };
  55103. /**
  55104. * Returns a string to use to update the GPU particles update shader
  55105. * @returns a string containng the defines string
  55106. */
  55107. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55108. return "#define CONEEMITTER";
  55109. };
  55110. /**
  55111. * Returns the string "BoxEmitter"
  55112. * @returns a string containing the class name
  55113. */
  55114. ConeParticleEmitter.prototype.getClassName = function () {
  55115. return "ConeEmitter";
  55116. };
  55117. /**
  55118. * Serializes the particle system to a JSON object.
  55119. * @returns the JSON object
  55120. */
  55121. ConeParticleEmitter.prototype.serialize = function () {
  55122. var serializationObject = {};
  55123. serializationObject.type = this.getClassName();
  55124. serializationObject.radius = this.radius;
  55125. serializationObject.angle = this.angle;
  55126. serializationObject.directionRandomizer = this.directionRandomizer;
  55127. return serializationObject;
  55128. };
  55129. /**
  55130. * Parse properties from a JSON object
  55131. * @param serializationObject defines the JSON object
  55132. */
  55133. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55134. this.radius = serializationObject.radius;
  55135. this.angle = serializationObject.angle;
  55136. this.directionRandomizer = serializationObject.directionRandomizer;
  55137. };
  55138. return ConeParticleEmitter;
  55139. }());
  55140. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55141. })(BABYLON || (BABYLON = {}));
  55142. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55143. "use strict";
  55144. var BABYLON;
  55145. (function (BABYLON) {
  55146. /**
  55147. * Particle emitter emitting particles from the inside of a sphere.
  55148. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55149. */
  55150. var SphereParticleEmitter = /** @class */ (function () {
  55151. /**
  55152. * Creates a new instance SphereParticleEmitter
  55153. * @param radius the radius of the emission sphere (1 by default)
  55154. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55155. */
  55156. function SphereParticleEmitter(
  55157. /**
  55158. * The radius of the emission sphere.
  55159. */
  55160. radius,
  55161. /**
  55162. * How much to randomize the particle direction [0-1].
  55163. */
  55164. directionRandomizer) {
  55165. if (radius === void 0) { radius = 1; }
  55166. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55167. this.radius = radius;
  55168. this.directionRandomizer = directionRandomizer;
  55169. }
  55170. /**
  55171. * Called by the particle System when the direction is computed for the created particle.
  55172. * @param emitPower is the power of the particle (speed)
  55173. * @param worldMatrix is the world matrix of the particle system
  55174. * @param directionToUpdate is the direction vector to update with the result
  55175. * @param particle is the particle we are computed the direction for
  55176. */
  55177. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55178. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55179. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55180. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55181. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55182. direction.x += randX;
  55183. direction.y += randY;
  55184. direction.z += randZ;
  55185. direction.normalize();
  55186. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55187. };
  55188. /**
  55189. * Called by the particle System when the position is computed for the created particle.
  55190. * @param worldMatrix is the world matrix of the particle system
  55191. * @param positionToUpdate is the position vector to update with the result
  55192. * @param particle is the particle we are computed the position for
  55193. */
  55194. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55195. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55196. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55197. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55198. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55199. var randY = randRadius * Math.cos(theta);
  55200. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55201. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55202. };
  55203. /**
  55204. * Clones the current emitter and returns a copy of it
  55205. * @returns the new emitter
  55206. */
  55207. SphereParticleEmitter.prototype.clone = function () {
  55208. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55209. BABYLON.Tools.DeepCopy(this, newOne);
  55210. return newOne;
  55211. };
  55212. /**
  55213. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55214. * @param effect defines the update shader
  55215. */
  55216. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55217. effect.setFloat("radius", this.radius);
  55218. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55219. };
  55220. /**
  55221. * Returns a string to use to update the GPU particles update shader
  55222. * @returns a string containng the defines string
  55223. */
  55224. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55225. return "#define SPHEREEMITTER";
  55226. };
  55227. /**
  55228. * Returns the string "SphereParticleEmitter"
  55229. * @returns a string containing the class name
  55230. */
  55231. SphereParticleEmitter.prototype.getClassName = function () {
  55232. return "SphereParticleEmitter";
  55233. };
  55234. /**
  55235. * Serializes the particle system to a JSON object.
  55236. * @returns the JSON object
  55237. */
  55238. SphereParticleEmitter.prototype.serialize = function () {
  55239. var serializationObject = {};
  55240. serializationObject.type = this.getClassName();
  55241. serializationObject.radius = this.radius;
  55242. serializationObject.directionRandomizer = this.directionRandomizer;
  55243. return serializationObject;
  55244. };
  55245. /**
  55246. * Parse properties from a JSON object
  55247. * @param serializationObject defines the JSON object
  55248. */
  55249. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55250. this.radius = serializationObject.radius;
  55251. this.directionRandomizer = serializationObject.directionRandomizer;
  55252. };
  55253. return SphereParticleEmitter;
  55254. }());
  55255. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55256. /**
  55257. * Particle emitter emitting particles from the inside of a sphere.
  55258. * It emits the particles randomly between two vectors.
  55259. */
  55260. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55261. __extends(SphereDirectedParticleEmitter, _super);
  55262. /**
  55263. * Creates a new instance SphereDirectedParticleEmitter
  55264. * @param radius the radius of the emission sphere (1 by default)
  55265. * @param direction1 the min limit of the emission direction (up vector by default)
  55266. * @param direction2 the max limit of the emission direction (up vector by default)
  55267. */
  55268. function SphereDirectedParticleEmitter(radius,
  55269. /**
  55270. * The min limit of the emission direction.
  55271. */
  55272. direction1,
  55273. /**
  55274. * The max limit of the emission direction.
  55275. */
  55276. direction2) {
  55277. if (radius === void 0) { radius = 1; }
  55278. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55279. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55280. var _this = _super.call(this, radius) || this;
  55281. _this.direction1 = direction1;
  55282. _this.direction2 = direction2;
  55283. return _this;
  55284. }
  55285. /**
  55286. * Called by the particle System when the direction is computed for the created particle.
  55287. * @param emitPower is the power of the particle (speed)
  55288. * @param worldMatrix is the world matrix of the particle system
  55289. * @param directionToUpdate is the direction vector to update with the result
  55290. * @param particle is the particle we are computed the direction for
  55291. */
  55292. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55293. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55294. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55295. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55296. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55297. };
  55298. /**
  55299. * Clones the current emitter and returns a copy of it
  55300. * @returns the new emitter
  55301. */
  55302. SphereDirectedParticleEmitter.prototype.clone = function () {
  55303. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55304. BABYLON.Tools.DeepCopy(this, newOne);
  55305. return newOne;
  55306. };
  55307. /**
  55308. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55309. * @param effect defines the update shader
  55310. */
  55311. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55312. effect.setFloat("radius", this.radius);
  55313. effect.setVector3("direction1", this.direction1);
  55314. effect.setVector3("direction2", this.direction2);
  55315. };
  55316. /**
  55317. * Returns a string to use to update the GPU particles update shader
  55318. * @returns a string containng the defines string
  55319. */
  55320. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55321. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55322. };
  55323. /**
  55324. * Returns the string "SphereDirectedParticleEmitter"
  55325. * @returns a string containing the class name
  55326. */
  55327. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55328. return "SphereDirectedParticleEmitter";
  55329. };
  55330. /**
  55331. * Serializes the particle system to a JSON object.
  55332. * @returns the JSON object
  55333. */
  55334. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55335. var serializationObject = _super.prototype.serialize.call(this);
  55336. ;
  55337. serializationObject.direction1 = this.direction1.asArray();
  55338. ;
  55339. serializationObject.direction2 = this.direction2.asArray();
  55340. ;
  55341. return serializationObject;
  55342. };
  55343. /**
  55344. * Parse properties from a JSON object
  55345. * @param serializationObject defines the JSON object
  55346. */
  55347. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55348. _super.prototype.parse.call(this, serializationObject);
  55349. this.direction1.copyFrom(serializationObject.direction1);
  55350. this.direction2.copyFrom(serializationObject.direction2);
  55351. };
  55352. return SphereDirectedParticleEmitter;
  55353. }(SphereParticleEmitter));
  55354. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55355. })(BABYLON || (BABYLON = {}));
  55356. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55357. "use strict";
  55358. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55359. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55360. s = arguments[i];
  55361. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55362. t[p] = s[p];
  55363. }
  55364. return t;
  55365. };
  55366. var BABYLON;
  55367. (function (BABYLON) {
  55368. /**
  55369. * This represents a GPU particle system in Babylon
  55370. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55371. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55372. */
  55373. var GPUParticleSystem = /** @class */ (function () {
  55374. /**
  55375. * Instantiates a GPU particle system.
  55376. * 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.
  55377. * @param name The name of the particle system
  55378. * @param capacity The max number of particles alive at the same time
  55379. * @param scene The scene the particle system belongs to
  55380. */
  55381. function GPUParticleSystem(name, options, scene) {
  55382. /**
  55383. * The emitter represents the Mesh or position we are attaching the particle system to.
  55384. */
  55385. this.emitter = null;
  55386. /**
  55387. * The rendering group used by the Particle system to chose when to render.
  55388. */
  55389. this.renderingGroupId = 0;
  55390. /**
  55391. * The layer mask we are rendering the particles through.
  55392. */
  55393. this.layerMask = 0x0FFFFFFF;
  55394. this._targetIndex = 0;
  55395. this._currentRenderId = -1;
  55396. this._started = false;
  55397. this._stopped = false;
  55398. this._timeDelta = 0;
  55399. this._attributesStrideSize = 14;
  55400. this._actualFrame = 0;
  55401. /**
  55402. * List of animations used by the particle system.
  55403. */
  55404. this.animations = [];
  55405. /**
  55406. * An event triggered when the system is disposed.
  55407. */
  55408. this.onDisposeObservable = new BABYLON.Observable();
  55409. /**
  55410. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55411. */
  55412. this.updateSpeed = 0.01;
  55413. /**
  55414. * The amount of time the particle system is running (depends of the overall update speed).
  55415. */
  55416. this.targetStopDuration = 0;
  55417. /**
  55418. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55419. */
  55420. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55421. /**
  55422. * Minimum life time of emitting particles.
  55423. */
  55424. this.minLifeTime = 1;
  55425. /**
  55426. * Maximum life time of emitting particles.
  55427. */
  55428. this.maxLifeTime = 1;
  55429. /**
  55430. * Minimum Size of emitting particles.
  55431. */
  55432. this.minSize = 1;
  55433. /**
  55434. * Maximum Size of emitting particles.
  55435. */
  55436. this.maxSize = 1;
  55437. /**
  55438. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55439. */
  55440. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55441. /**
  55442. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55443. */
  55444. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55445. /**
  55446. * Color the particle will have at the end of its lifetime.
  55447. */
  55448. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  55449. /**
  55450. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  55451. */
  55452. this.emitRate = 100;
  55453. /**
  55454. * You can use gravity if you want to give an orientation to your particles.
  55455. */
  55456. this.gravity = BABYLON.Vector3.Zero();
  55457. /**
  55458. * Minimum power of emitting particles.
  55459. */
  55460. this.minEmitPower = 1;
  55461. /**
  55462. * Maximum power of emitting particles.
  55463. */
  55464. this.maxEmitPower = 1;
  55465. /**
  55466. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55467. * to override the particles.
  55468. */
  55469. this.forceDepthWrite = false;
  55470. this.id = name;
  55471. this.name = name;
  55472. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55473. this._engine = this._scene.getEngine();
  55474. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  55475. this._capacity = fullOptions.capacity;
  55476. this._activeCount = fullOptions.capacity;
  55477. this._currentActiveCount = 0;
  55478. this._scene.particleSystems.push(this);
  55479. this._updateEffectOptions = {
  55480. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  55481. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  55482. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  55483. uniformBuffersNames: [],
  55484. samplers: ["randomSampler"],
  55485. defines: "",
  55486. fallbacks: null,
  55487. onCompiled: null,
  55488. onError: null,
  55489. indexParameters: null,
  55490. maxSimultaneousLights: 0,
  55491. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  55492. };
  55493. // Random data
  55494. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  55495. var d = [];
  55496. for (var i = 0; i < maxTextureSize; ++i) {
  55497. d.push(Math.random());
  55498. d.push(Math.random());
  55499. d.push(Math.random());
  55500. d.push(Math.random());
  55501. }
  55502. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  55503. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55504. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55505. this._randomTextureSize = maxTextureSize;
  55506. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55507. }
  55508. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  55509. /**
  55510. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  55511. */
  55512. get: function () {
  55513. if (!BABYLON.Engine.LastCreatedEngine) {
  55514. return false;
  55515. }
  55516. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  55517. },
  55518. enumerable: true,
  55519. configurable: true
  55520. });
  55521. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  55522. /**
  55523. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55524. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55525. */
  55526. get: function () {
  55527. if (this.particleEmitterType.direction1) {
  55528. return this.particleEmitterType.direction1;
  55529. }
  55530. return BABYLON.Vector3.Zero();
  55531. },
  55532. set: function (value) {
  55533. if (this.particleEmitterType.direction1) {
  55534. this.particleEmitterType.direction1 = value;
  55535. }
  55536. },
  55537. enumerable: true,
  55538. configurable: true
  55539. });
  55540. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  55541. /**
  55542. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55543. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55544. */
  55545. get: function () {
  55546. if (this.particleEmitterType.direction2) {
  55547. return this.particleEmitterType.direction2;
  55548. }
  55549. return BABYLON.Vector3.Zero();
  55550. },
  55551. set: function (value) {
  55552. if (this.particleEmitterType.direction2) {
  55553. this.particleEmitterType.direction2 = value;
  55554. }
  55555. },
  55556. enumerable: true,
  55557. configurable: true
  55558. });
  55559. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  55560. /**
  55561. * 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.
  55562. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55563. */
  55564. get: function () {
  55565. if (this.particleEmitterType.minEmitBox) {
  55566. return this.particleEmitterType.minEmitBox;
  55567. }
  55568. return BABYLON.Vector3.Zero();
  55569. },
  55570. set: function (value) {
  55571. if (this.particleEmitterType.minEmitBox) {
  55572. this.particleEmitterType.minEmitBox = value;
  55573. }
  55574. },
  55575. enumerable: true,
  55576. configurable: true
  55577. });
  55578. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  55579. /**
  55580. * 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.
  55581. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55582. */
  55583. get: function () {
  55584. if (this.particleEmitterType.maxEmitBox) {
  55585. return this.particleEmitterType.maxEmitBox;
  55586. }
  55587. return BABYLON.Vector3.Zero();
  55588. },
  55589. set: function (value) {
  55590. if (this.particleEmitterType.maxEmitBox) {
  55591. this.particleEmitterType.maxEmitBox = value;
  55592. }
  55593. },
  55594. enumerable: true,
  55595. configurable: true
  55596. });
  55597. /**
  55598. * Gets the maximum number of particles active at the same time.
  55599. * @returns The max number of active particles.
  55600. */
  55601. GPUParticleSystem.prototype.getCapacity = function () {
  55602. return this._capacity;
  55603. };
  55604. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  55605. /**
  55606. * Gets or set the number of active particles
  55607. */
  55608. get: function () {
  55609. return this._activeCount;
  55610. },
  55611. set: function (value) {
  55612. this._activeCount = Math.min(value, this._capacity);
  55613. },
  55614. enumerable: true,
  55615. configurable: true
  55616. });
  55617. /**
  55618. * Is this system ready to be used/rendered
  55619. * @return true if the system is ready
  55620. */
  55621. GPUParticleSystem.prototype.isReady = function () {
  55622. if (!this._updateEffect) {
  55623. this._recreateUpdateEffect();
  55624. this._recreateRenderEffect();
  55625. return false;
  55626. }
  55627. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55628. return false;
  55629. }
  55630. return true;
  55631. };
  55632. /**
  55633. * Gets Wether the system has been started.
  55634. * @returns True if it has been started, otherwise false.
  55635. */
  55636. GPUParticleSystem.prototype.isStarted = function () {
  55637. return this._started;
  55638. };
  55639. /**
  55640. * Starts the particle system and begins to emit.
  55641. */
  55642. GPUParticleSystem.prototype.start = function () {
  55643. this._started = true;
  55644. this._stopped = false;
  55645. };
  55646. /**
  55647. * Stops the particle system.
  55648. */
  55649. GPUParticleSystem.prototype.stop = function () {
  55650. this._stopped = true;
  55651. };
  55652. /**
  55653. * Remove all active particles
  55654. */
  55655. GPUParticleSystem.prototype.reset = function () {
  55656. this._releaseBuffers();
  55657. this._releaseVAOs();
  55658. this._currentActiveCount = 0;
  55659. this._targetIndex = 0;
  55660. };
  55661. /**
  55662. * Returns the string "GPUParticleSystem"
  55663. * @returns a string containing the class name
  55664. */
  55665. GPUParticleSystem.prototype.getClassName = function () {
  55666. return "GPUParticleSystem";
  55667. };
  55668. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  55669. var updateVertexBuffers = {};
  55670. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  55671. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  55672. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  55673. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  55674. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  55675. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  55676. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  55677. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  55678. this._engine.bindArrayBuffer(null);
  55679. return vao;
  55680. };
  55681. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  55682. var renderVertexBuffers = {};
  55683. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  55684. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  55685. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  55686. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  55687. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  55688. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  55689. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  55690. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  55691. this._engine.bindArrayBuffer(null);
  55692. return vao;
  55693. };
  55694. GPUParticleSystem.prototype._initialize = function (force) {
  55695. if (force === void 0) { force = false; }
  55696. if (this._buffer0 && !force) {
  55697. return;
  55698. }
  55699. var engine = this._scene.getEngine();
  55700. var data = new Array();
  55701. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  55702. // position
  55703. data.push(0.0);
  55704. data.push(0.0);
  55705. data.push(0.0);
  55706. // Age and life
  55707. data.push(0.0); // create the particle as a dead one to create a new one at start
  55708. data.push(0.0);
  55709. // Seed
  55710. data.push(Math.random());
  55711. // Size
  55712. data.push(0.0);
  55713. // color
  55714. data.push(0.0);
  55715. data.push(0.0);
  55716. data.push(0.0);
  55717. data.push(0.0);
  55718. // direction
  55719. data.push(0.0);
  55720. data.push(0.0);
  55721. data.push(0.0);
  55722. }
  55723. // Sprite data
  55724. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  55725. -0.5, 0.5, 0, 1,
  55726. -0.5, -0.5, 0, 0,
  55727. 0.5, -0.5, 1, 0]);
  55728. // Buffers
  55729. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  55730. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  55731. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  55732. // Update VAO
  55733. this._updateVAO = [];
  55734. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  55735. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  55736. // Render VAO
  55737. this._renderVAO = [];
  55738. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  55739. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  55740. // Links
  55741. this._sourceBuffer = this._buffer0;
  55742. this._targetBuffer = this._buffer1;
  55743. };
  55744. /** @ignore */
  55745. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  55746. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  55747. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  55748. return;
  55749. }
  55750. this._updateEffectOptions.defines = defines;
  55751. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  55752. };
  55753. /** @ignore */
  55754. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  55755. var defines = "";
  55756. if (this._scene.clipPlane) {
  55757. defines = "\n#define CLIPPLANE";
  55758. }
  55759. if (this._renderEffect && this._renderEffect.defines === defines) {
  55760. return;
  55761. }
  55762. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  55763. };
  55764. /**
  55765. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55766. */
  55767. GPUParticleSystem.prototype.animate = function () {
  55768. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  55769. this._actualFrame += this._timeDelta;
  55770. if (!this._stopped) {
  55771. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  55772. this.stop();
  55773. }
  55774. }
  55775. };
  55776. /**
  55777. * Renders the particle system in its current state.
  55778. * @returns the current number of particles
  55779. */
  55780. GPUParticleSystem.prototype.render = function () {
  55781. if (!this._started) {
  55782. return 0;
  55783. }
  55784. this._recreateUpdateEffect();
  55785. this._recreateRenderEffect();
  55786. if (!this.isReady()) {
  55787. return 0;
  55788. }
  55789. if (this._currentRenderId === this._scene.getRenderId()) {
  55790. return 0;
  55791. }
  55792. this._currentRenderId = this._scene.getRenderId();
  55793. // Get everything ready to render
  55794. this._initialize();
  55795. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  55796. // Enable update effect
  55797. this._engine.enableEffect(this._updateEffect);
  55798. this._engine.setState(false);
  55799. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  55800. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  55801. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  55802. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  55803. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  55804. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  55805. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  55806. this._updateEffect.setDirectColor4("color1", this.color1);
  55807. this._updateEffect.setDirectColor4("color2", this.color2);
  55808. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  55809. this._updateEffect.setVector3("gravity", this.gravity);
  55810. if (this.particleEmitterType) {
  55811. this.particleEmitterType.applyToShader(this._updateEffect);
  55812. }
  55813. var emitterWM;
  55814. if (this.emitter.position) {
  55815. var emitterMesh = this.emitter;
  55816. emitterWM = emitterMesh.getWorldMatrix();
  55817. }
  55818. else {
  55819. var emitterPosition = this.emitter;
  55820. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55821. }
  55822. this._updateEffect.setMatrix("emitterWM", emitterWM);
  55823. // Bind source VAO
  55824. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  55825. // Update
  55826. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  55827. this._engine.setRasterizerState(false);
  55828. this._engine.beginTransformFeedback();
  55829. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  55830. this._engine.endTransformFeedback();
  55831. this._engine.setRasterizerState(true);
  55832. this._engine.bindTransformFeedbackBuffer(null);
  55833. // Enable render effect
  55834. this._engine.enableEffect(this._renderEffect);
  55835. var viewMatrix = this._scene.getViewMatrix();
  55836. this._renderEffect.setMatrix("view", viewMatrix);
  55837. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  55838. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  55839. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  55840. if (this._scene.clipPlane) {
  55841. var clipPlane = this._scene.clipPlane;
  55842. var invView = viewMatrix.clone();
  55843. invView.invert();
  55844. this._renderEffect.setMatrix("invView", invView);
  55845. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55846. }
  55847. // Draw order
  55848. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  55849. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55850. }
  55851. else {
  55852. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55853. }
  55854. if (this.forceDepthWrite) {
  55855. this._engine.setDepthWrite(true);
  55856. }
  55857. // Bind source VAO
  55858. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  55859. // Render
  55860. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  55861. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55862. // Switch VAOs
  55863. this._targetIndex++;
  55864. if (this._targetIndex === 2) {
  55865. this._targetIndex = 0;
  55866. }
  55867. // Switch buffers
  55868. var tmpBuffer = this._sourceBuffer;
  55869. this._sourceBuffer = this._targetBuffer;
  55870. this._targetBuffer = tmpBuffer;
  55871. return this._currentActiveCount;
  55872. };
  55873. /**
  55874. * Rebuilds the particle system
  55875. */
  55876. GPUParticleSystem.prototype.rebuild = function () {
  55877. this._initialize(true);
  55878. };
  55879. GPUParticleSystem.prototype._releaseBuffers = function () {
  55880. if (this._buffer0) {
  55881. this._buffer0.dispose();
  55882. this._buffer0 = null;
  55883. }
  55884. if (this._buffer1) {
  55885. this._buffer1.dispose();
  55886. this._buffer1 = null;
  55887. }
  55888. if (this._spriteBuffer) {
  55889. this._spriteBuffer.dispose();
  55890. this._spriteBuffer = null;
  55891. }
  55892. };
  55893. GPUParticleSystem.prototype._releaseVAOs = function () {
  55894. if (!this._updateVAO) {
  55895. return;
  55896. }
  55897. for (var index = 0; index < this._updateVAO.length; index++) {
  55898. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  55899. }
  55900. this._updateVAO = [];
  55901. for (var index = 0; index < this._renderVAO.length; index++) {
  55902. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  55903. }
  55904. this._renderVAO = [];
  55905. };
  55906. /**
  55907. * Disposes the particle system and free the associated resources
  55908. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55909. */
  55910. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  55911. if (disposeTexture === void 0) { disposeTexture = true; }
  55912. var index = this._scene.particleSystems.indexOf(this);
  55913. if (index > -1) {
  55914. this._scene.particleSystems.splice(index, 1);
  55915. }
  55916. this._releaseBuffers();
  55917. this._releaseVAOs();
  55918. if (this._randomTexture) {
  55919. this._randomTexture.dispose();
  55920. this._randomTexture = null;
  55921. }
  55922. if (disposeTexture && this.particleTexture) {
  55923. this.particleTexture.dispose();
  55924. this.particleTexture = null;
  55925. }
  55926. // Callback
  55927. this.onDisposeObservable.notifyObservers(this);
  55928. this.onDisposeObservable.clear();
  55929. };
  55930. /**
  55931. * Clones the particle system.
  55932. * @param name The name of the cloned object
  55933. * @param newEmitter The new emitter to use
  55934. * @returns the cloned particle system
  55935. */
  55936. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  55937. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  55938. BABYLON.Tools.DeepCopy(this, result);
  55939. if (newEmitter === undefined) {
  55940. newEmitter = this.emitter;
  55941. }
  55942. result.emitter = newEmitter;
  55943. if (this.particleTexture) {
  55944. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55945. }
  55946. return result;
  55947. };
  55948. /**
  55949. * Serializes the particle system to a JSON object.
  55950. * @returns the JSON object
  55951. */
  55952. GPUParticleSystem.prototype.serialize = function () {
  55953. var serializationObject = {};
  55954. serializationObject.name = this.name;
  55955. serializationObject.id = this.id;
  55956. // Emitter
  55957. if (this.emitter.position) {
  55958. var emitterMesh = this.emitter;
  55959. serializationObject.emitterId = emitterMesh.id;
  55960. }
  55961. else {
  55962. var emitterPosition = this.emitter;
  55963. serializationObject.emitter = emitterPosition.asArray();
  55964. }
  55965. serializationObject.capacity = this.getCapacity();
  55966. if (this.particleTexture) {
  55967. serializationObject.textureName = this.particleTexture.name;
  55968. }
  55969. // Animations
  55970. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55971. // Particle system
  55972. serializationObject.activeParticleCount = this.activeParticleCount;
  55973. serializationObject.randomTextureSize = this._randomTextureSize;
  55974. serializationObject.minSize = this.minSize;
  55975. serializationObject.maxSize = this.maxSize;
  55976. serializationObject.minEmitPower = this.minEmitPower;
  55977. serializationObject.maxEmitPower = this.maxEmitPower;
  55978. serializationObject.minLifeTime = this.minLifeTime;
  55979. serializationObject.maxLifeTime = this.maxLifeTime;
  55980. serializationObject.emitRate = this.emitRate;
  55981. serializationObject.gravity = this.gravity.asArray();
  55982. serializationObject.color1 = this.color1.asArray();
  55983. serializationObject.color2 = this.color2.asArray();
  55984. serializationObject.colorDead = this.colorDead.asArray();
  55985. serializationObject.updateSpeed = this.updateSpeed;
  55986. serializationObject.targetStopDuration = this.targetStopDuration;
  55987. serializationObject.blendMode = this.blendMode;
  55988. // Emitter
  55989. if (this.particleEmitterType) {
  55990. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55991. }
  55992. return serializationObject;
  55993. };
  55994. /**
  55995. * Parses a JSON object to create a GPU particle system.
  55996. * @param parsedParticleSystem The JSON object to parse
  55997. * @param scene The scene to create the particle system in
  55998. * @param rootUrl The root url to use to load external dependencies like texture
  55999. * @returns the parsed GPU particle system
  56000. */
  56001. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56002. var name = parsedParticleSystem.name;
  56003. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56004. if (parsedParticleSystem.id) {
  56005. particleSystem.id = parsedParticleSystem.id;
  56006. }
  56007. // Texture
  56008. if (parsedParticleSystem.textureName) {
  56009. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56010. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56011. }
  56012. // Emitter
  56013. if (parsedParticleSystem.emitterId) {
  56014. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56015. }
  56016. else {
  56017. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56018. }
  56019. // Animations
  56020. if (parsedParticleSystem.animations) {
  56021. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56022. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56023. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56024. }
  56025. }
  56026. // Particle system
  56027. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56028. particleSystem.minSize = parsedParticleSystem.minSize;
  56029. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56030. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56031. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56032. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56033. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56034. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56035. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56036. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56037. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56038. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56039. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56040. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56041. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56042. // Emitter
  56043. if (parsedParticleSystem.particleEmitterType) {
  56044. var emitterType = void 0;
  56045. switch (parsedParticleSystem.particleEmitterType.type) {
  56046. case "SphereEmitter":
  56047. emitterType = new BABYLON.SphereParticleEmitter();
  56048. break;
  56049. case "SphereDirectedParticleEmitter":
  56050. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56051. break;
  56052. case "ConeEmitter":
  56053. emitterType = new BABYLON.ConeParticleEmitter();
  56054. break;
  56055. case "BoxEmitter":
  56056. default:
  56057. emitterType = new BABYLON.BoxParticleEmitter();
  56058. break;
  56059. }
  56060. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56061. particleSystem.particleEmitterType = emitterType;
  56062. }
  56063. return particleSystem;
  56064. };
  56065. return GPUParticleSystem;
  56066. }());
  56067. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56068. })(BABYLON || (BABYLON = {}));
  56069. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56070. "use strict";
  56071. var BABYLON;
  56072. (function (BABYLON) {
  56073. /**
  56074. * Represents one particle of a solid particle system.
  56075. */
  56076. var SolidParticle = /** @class */ (function () {
  56077. /**
  56078. * Creates a Solid Particle object.
  56079. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56080. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56081. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56082. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56083. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56084. * @param shapeId (integer) is the model shape identifier in the SPS.
  56085. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56086. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56087. */
  56088. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56089. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56090. /**
  56091. * particle global index
  56092. */
  56093. this.idx = 0;
  56094. /**
  56095. * The color of the particle
  56096. */
  56097. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56098. /**
  56099. * The world space position of the particle.
  56100. */
  56101. this.position = BABYLON.Vector3.Zero();
  56102. /**
  56103. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56104. */
  56105. this.rotation = BABYLON.Vector3.Zero();
  56106. /**
  56107. * The scaling of the particle.
  56108. */
  56109. this.scaling = BABYLON.Vector3.One();
  56110. /**
  56111. * The uvs of the particle.
  56112. */
  56113. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56114. /**
  56115. * The current speed of the particle.
  56116. */
  56117. this.velocity = BABYLON.Vector3.Zero();
  56118. /**
  56119. * The pivot point in the particle local space.
  56120. */
  56121. this.pivot = BABYLON.Vector3.Zero();
  56122. /**
  56123. * Must the particle be translated from its pivot point in its local space ?
  56124. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56125. * Default : false
  56126. */
  56127. this.translateFromPivot = false;
  56128. /**
  56129. * Is the particle active or not ?
  56130. */
  56131. this.alive = true;
  56132. /**
  56133. * Is the particle visible or not ?
  56134. */
  56135. this.isVisible = true;
  56136. /**
  56137. * Index of this particle in the global "positions" array (Internal use)
  56138. */
  56139. this._pos = 0;
  56140. /**
  56141. * Index of this particle in the global "indices" array (Internal use)
  56142. */
  56143. this._ind = 0;
  56144. /**
  56145. * ModelShape id of this particle
  56146. */
  56147. this.shapeId = 0;
  56148. /**
  56149. * Index of the particle in its shape id (Internal use)
  56150. */
  56151. this.idxInShape = 0;
  56152. /**
  56153. * Still set as invisible in order to skip useless computations (Internal use)
  56154. */
  56155. this._stillInvisible = false;
  56156. /**
  56157. * Last computed particle rotation matrix
  56158. */
  56159. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56160. /**
  56161. * Parent particle Id, if any.
  56162. * Default null.
  56163. */
  56164. this.parentId = null;
  56165. /**
  56166. * Internal global position in the SPS.
  56167. */
  56168. this._globalPosition = BABYLON.Vector3.Zero();
  56169. this.idx = particleIndex;
  56170. this._pos = positionIndex;
  56171. this._ind = indiceIndex;
  56172. this._model = model;
  56173. this.shapeId = shapeId;
  56174. this.idxInShape = idxInShape;
  56175. this._sps = sps;
  56176. if (modelBoundingInfo) {
  56177. this._modelBoundingInfo = modelBoundingInfo;
  56178. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56179. }
  56180. }
  56181. Object.defineProperty(SolidParticle.prototype, "scale", {
  56182. /**
  56183. * Legacy support, changed scale to scaling
  56184. */
  56185. get: function () {
  56186. return this.scaling;
  56187. },
  56188. /**
  56189. * Legacy support, changed scale to scaling
  56190. */
  56191. set: function (scale) {
  56192. this.scaling = scale;
  56193. },
  56194. enumerable: true,
  56195. configurable: true
  56196. });
  56197. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56198. /**
  56199. * Legacy support, changed quaternion to rotationQuaternion
  56200. */
  56201. get: function () {
  56202. return this.rotationQuaternion;
  56203. },
  56204. /**
  56205. * Legacy support, changed quaternion to rotationQuaternion
  56206. */
  56207. set: function (q) {
  56208. this.rotationQuaternion = q;
  56209. },
  56210. enumerable: true,
  56211. configurable: true
  56212. });
  56213. /**
  56214. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56215. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56216. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56217. * @returns true if it intersects
  56218. */
  56219. SolidParticle.prototype.intersectsMesh = function (target) {
  56220. if (!this._boundingInfo || !target._boundingInfo) {
  56221. return false;
  56222. }
  56223. if (this._sps._bSphereOnly) {
  56224. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56225. }
  56226. return this._boundingInfo.intersects(target._boundingInfo, false);
  56227. };
  56228. return SolidParticle;
  56229. }());
  56230. BABYLON.SolidParticle = SolidParticle;
  56231. /**
  56232. * Represents the shape of the model used by one particle of a solid particle system.
  56233. * SPS internal tool, don't use it manually.
  56234. */
  56235. var ModelShape = /** @class */ (function () {
  56236. /**
  56237. * 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.
  56238. * SPS internal tool, don't use it manually.
  56239. * @ignore
  56240. */
  56241. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56242. /**
  56243. * length of the shape in the model indices array (internal use)
  56244. */
  56245. this._indicesLength = 0;
  56246. this.shapeID = id;
  56247. this._shape = shape;
  56248. this._indicesLength = indicesLength;
  56249. this._shapeUV = shapeUV;
  56250. this._positionFunction = posFunction;
  56251. this._vertexFunction = vtxFunction;
  56252. }
  56253. return ModelShape;
  56254. }());
  56255. BABYLON.ModelShape = ModelShape;
  56256. /**
  56257. * Represents a Depth Sorted Particle in the solid particle system.
  56258. */
  56259. var DepthSortedParticle = /** @class */ (function () {
  56260. function DepthSortedParticle() {
  56261. /**
  56262. * Index of the particle in the "indices" array
  56263. */
  56264. this.ind = 0;
  56265. /**
  56266. * Length of the particle shape in the "indices" array
  56267. */
  56268. this.indicesLength = 0;
  56269. /**
  56270. * Squared distance from the particle to the camera
  56271. */
  56272. this.sqDistance = 0.0;
  56273. }
  56274. return DepthSortedParticle;
  56275. }());
  56276. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56277. })(BABYLON || (BABYLON = {}));
  56278. //# sourceMappingURL=babylon.solidParticle.js.map
  56279. "use strict";
  56280. var BABYLON;
  56281. (function (BABYLON) {
  56282. /**
  56283. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56284. *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.
  56285. * The SPS is also a particle system. It provides some methods to manage the particles.
  56286. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56287. *
  56288. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56289. */
  56290. var SolidParticleSystem = /** @class */ (function () {
  56291. /**
  56292. * Creates a SPS (Solid Particle System) object.
  56293. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56294. * @param scene (Scene) is the scene in which the SPS is added.
  56295. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56296. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56297. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56298. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56299. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56300. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56301. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56302. */
  56303. function SolidParticleSystem(name, scene, options) {
  56304. /**
  56305. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56306. * Example : var p = SPS.particles[i];
  56307. */
  56308. this.particles = new Array();
  56309. /**
  56310. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56311. */
  56312. this.nbParticles = 0;
  56313. /**
  56314. * If the particles must ever face the camera (default false). Useful for planar particles.
  56315. */
  56316. this.billboard = false;
  56317. /**
  56318. * Recompute normals when adding a shape
  56319. */
  56320. this.recomputeNormals = true;
  56321. /**
  56322. * This a counter ofr your own usage. It's not set by any SPS functions.
  56323. */
  56324. this.counter = 0;
  56325. /**
  56326. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56327. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56328. */
  56329. this.vars = {};
  56330. /**
  56331. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56332. */
  56333. this._bSphereOnly = false;
  56334. /**
  56335. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56336. */
  56337. this._bSphereRadiusFactor = 1.0;
  56338. this._positions = new Array();
  56339. this._indices = new Array();
  56340. this._normals = new Array();
  56341. this._colors = new Array();
  56342. this._uvs = new Array();
  56343. this._index = 0; // indices index
  56344. this._updatable = true;
  56345. this._pickable = false;
  56346. this._isVisibilityBoxLocked = false;
  56347. this._alwaysVisible = false;
  56348. this._depthSort = false;
  56349. this._shapeCounter = 0;
  56350. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56351. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56352. this._computeParticleColor = true;
  56353. this._computeParticleTexture = true;
  56354. this._computeParticleRotation = true;
  56355. this._computeParticleVertex = false;
  56356. this._computeBoundingBox = false;
  56357. this._depthSortParticles = true;
  56358. this._cam_axisZ = BABYLON.Vector3.Zero();
  56359. this._cam_axisY = BABYLON.Vector3.Zero();
  56360. this._cam_axisX = BABYLON.Vector3.Zero();
  56361. this._axisZ = BABYLON.Axis.Z;
  56362. this._camDir = BABYLON.Vector3.Zero();
  56363. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56364. this._rotMatrix = new BABYLON.Matrix();
  56365. this._invertMatrix = new BABYLON.Matrix();
  56366. this._rotated = BABYLON.Vector3.Zero();
  56367. this._quaternion = new BABYLON.Quaternion();
  56368. this._vertex = BABYLON.Vector3.Zero();
  56369. this._normal = BABYLON.Vector3.Zero();
  56370. this._yaw = 0.0;
  56371. this._pitch = 0.0;
  56372. this._roll = 0.0;
  56373. this._halfroll = 0.0;
  56374. this._halfpitch = 0.0;
  56375. this._halfyaw = 0.0;
  56376. this._sinRoll = 0.0;
  56377. this._cosRoll = 0.0;
  56378. this._sinPitch = 0.0;
  56379. this._cosPitch = 0.0;
  56380. this._sinYaw = 0.0;
  56381. this._cosYaw = 0.0;
  56382. this._mustUnrotateFixedNormals = false;
  56383. this._minimum = BABYLON.Vector3.Zero();
  56384. this._maximum = BABYLON.Vector3.Zero();
  56385. this._minBbox = BABYLON.Vector3.Zero();
  56386. this._maxBbox = BABYLON.Vector3.Zero();
  56387. this._particlesIntersect = false;
  56388. this._depthSortFunction = function (p1, p2) {
  56389. return (p2.sqDistance - p1.sqDistance);
  56390. };
  56391. this._needs32Bits = false;
  56392. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  56393. this._scaledPivot = BABYLON.Vector3.Zero();
  56394. this._particleHasParent = false;
  56395. this.name = name;
  56396. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56397. this._camera = scene.activeCamera;
  56398. this._pickable = options ? options.isPickable : false;
  56399. this._depthSort = options ? options.enableDepthSort : false;
  56400. this._particlesIntersect = options ? options.particleIntersection : false;
  56401. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  56402. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  56403. if (options && options.updatable) {
  56404. this._updatable = options.updatable;
  56405. }
  56406. else {
  56407. this._updatable = true;
  56408. }
  56409. if (this._pickable) {
  56410. this.pickedParticles = [];
  56411. }
  56412. if (this._depthSort) {
  56413. this.depthSortedParticles = [];
  56414. }
  56415. }
  56416. /**
  56417. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56418. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56419. * @returns the created mesh
  56420. */
  56421. SolidParticleSystem.prototype.buildMesh = function () {
  56422. if (this.nbParticles === 0) {
  56423. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56424. this.addShape(triangle, 1);
  56425. triangle.dispose();
  56426. }
  56427. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  56428. this._positions32 = new Float32Array(this._positions);
  56429. this._uvs32 = new Float32Array(this._uvs);
  56430. this._colors32 = new Float32Array(this._colors);
  56431. if (this.recomputeNormals) {
  56432. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  56433. }
  56434. this._normals32 = new Float32Array(this._normals);
  56435. this._fixedNormal32 = new Float32Array(this._normals);
  56436. if (this._mustUnrotateFixedNormals) {
  56437. this._unrotateFixedNormals();
  56438. }
  56439. var vertexData = new BABYLON.VertexData();
  56440. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  56441. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56442. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56443. if (this._uvs32) {
  56444. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56445. ;
  56446. }
  56447. if (this._colors32) {
  56448. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56449. }
  56450. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56451. vertexData.applyToMesh(mesh, this._updatable);
  56452. this.mesh = mesh;
  56453. this.mesh.isPickable = this._pickable;
  56454. // free memory
  56455. if (!this._depthSort) {
  56456. this._indices = null;
  56457. }
  56458. this._positions = null;
  56459. this._normals = null;
  56460. this._uvs = null;
  56461. this._colors = null;
  56462. if (!this._updatable) {
  56463. this.particles.length = 0;
  56464. }
  56465. return mesh;
  56466. };
  56467. /**
  56468. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56469. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56470. * Thus the particles generated from `digest()` have their property `position` set yet.
  56471. * @param mesh ( Mesh ) is the mesh to be digested
  56472. * @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
  56473. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56474. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56475. * @returns the current SPS
  56476. */
  56477. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56478. var size = (options && options.facetNb) || 1;
  56479. var number = (options && options.number) || 0;
  56480. var delta = (options && options.delta) || 0;
  56481. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56482. var meshInd = mesh.getIndices();
  56483. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56484. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56485. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56486. var f = 0; // facet counter
  56487. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56488. // compute size from number
  56489. if (number) {
  56490. number = (number > totalFacets) ? totalFacets : number;
  56491. size = Math.round(totalFacets / number);
  56492. delta = 0;
  56493. }
  56494. else {
  56495. size = (size > totalFacets) ? totalFacets : size;
  56496. }
  56497. var facetPos = []; // submesh positions
  56498. var facetInd = []; // submesh indices
  56499. var facetUV = []; // submesh UV
  56500. var facetCol = []; // submesh colors
  56501. var barycenter = BABYLON.Vector3.Zero();
  56502. var sizeO = size;
  56503. while (f < totalFacets) {
  56504. size = sizeO + Math.floor((1 + delta) * Math.random());
  56505. if (f > totalFacets - size) {
  56506. size = totalFacets - f;
  56507. }
  56508. // reset temp arrays
  56509. facetPos.length = 0;
  56510. facetInd.length = 0;
  56511. facetUV.length = 0;
  56512. facetCol.length = 0;
  56513. // iterate over "size" facets
  56514. var fi = 0;
  56515. for (var j = f * 3; j < (f + size) * 3; j++) {
  56516. facetInd.push(fi);
  56517. var i = meshInd[j];
  56518. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56519. if (meshUV) {
  56520. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56521. }
  56522. if (meshCol) {
  56523. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56524. }
  56525. fi++;
  56526. }
  56527. // create a model shape for each single particle
  56528. var idx = this.nbParticles;
  56529. var shape = this._posToShape(facetPos);
  56530. var shapeUV = this._uvsToShapeUV(facetUV);
  56531. // compute the barycenter of the shape
  56532. var v;
  56533. for (v = 0; v < shape.length; v++) {
  56534. barycenter.addInPlace(shape[v]);
  56535. }
  56536. barycenter.scaleInPlace(1 / shape.length);
  56537. // shift the shape from its barycenter to the origin
  56538. for (v = 0; v < shape.length; v++) {
  56539. shape[v].subtractInPlace(barycenter);
  56540. }
  56541. var bInfo;
  56542. if (this._particlesIntersect) {
  56543. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  56544. }
  56545. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  56546. // add the particle in the SPS
  56547. var currentPos = this._positions.length;
  56548. var currentInd = this._indices.length;
  56549. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  56550. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  56551. // initialize the particle position
  56552. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56553. this._index += shape.length;
  56554. idx++;
  56555. this.nbParticles++;
  56556. this._shapeCounter++;
  56557. f += size;
  56558. }
  56559. return this;
  56560. };
  56561. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  56562. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  56563. var index = 0;
  56564. var idx = 0;
  56565. for (var p = 0; p < this.particles.length; p++) {
  56566. this._particle = this.particles[p];
  56567. this._shape = this._particle._model._shape;
  56568. if (this._particle.rotationQuaternion) {
  56569. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56570. }
  56571. else {
  56572. this._yaw = this._particle.rotation.y;
  56573. this._pitch = this._particle.rotation.x;
  56574. this._roll = this._particle.rotation.z;
  56575. this._quaternionRotationYPR();
  56576. }
  56577. this._quaternionToRotationMatrix();
  56578. this._rotMatrix.invertToRef(this._invertMatrix);
  56579. for (var pt = 0; pt < this._shape.length; pt++) {
  56580. idx = index + pt * 3;
  56581. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  56582. this._fixedNormal32[idx] = this._normal.x;
  56583. this._fixedNormal32[idx + 1] = this._normal.y;
  56584. this._fixedNormal32[idx + 2] = this._normal.z;
  56585. }
  56586. index = idx + 3;
  56587. }
  56588. };
  56589. //reset copy
  56590. SolidParticleSystem.prototype._resetCopy = function () {
  56591. this._copy.position.x = 0;
  56592. this._copy.position.y = 0;
  56593. this._copy.position.z = 0;
  56594. this._copy.rotation.x = 0;
  56595. this._copy.rotation.y = 0;
  56596. this._copy.rotation.z = 0;
  56597. this._copy.rotationQuaternion = null;
  56598. this._copy.scaling.x = 1.0;
  56599. this._copy.scaling.y = 1.0;
  56600. this._copy.scaling.z = 1.0;
  56601. this._copy.uvs.x = 0;
  56602. this._copy.uvs.y = 0;
  56603. this._copy.uvs.z = 1.0;
  56604. this._copy.uvs.w = 1.0;
  56605. this._copy.color = null;
  56606. this._copy.translateFromPivot = false;
  56607. };
  56608. // _meshBuilder : inserts the shape model in the global SPS mesh
  56609. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  56610. var i;
  56611. var u = 0;
  56612. var c = 0;
  56613. var n = 0;
  56614. this._resetCopy();
  56615. if (options && options.positionFunction) {
  56616. options.positionFunction(this._copy, idx, idxInShape);
  56617. this._mustUnrotateFixedNormals = true;
  56618. }
  56619. if (this._copy.rotationQuaternion) {
  56620. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56621. }
  56622. else {
  56623. this._yaw = this._copy.rotation.y;
  56624. this._pitch = this._copy.rotation.x;
  56625. this._roll = this._copy.rotation.z;
  56626. this._quaternionRotationYPR();
  56627. }
  56628. this._quaternionToRotationMatrix();
  56629. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  56630. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  56631. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  56632. if (this._copy.translateFromPivot) {
  56633. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56634. }
  56635. else {
  56636. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56637. }
  56638. for (i = 0; i < shape.length; i++) {
  56639. this._vertex.x = shape[i].x;
  56640. this._vertex.y = shape[i].y;
  56641. this._vertex.z = shape[i].z;
  56642. if (options && options.vertexFunction) {
  56643. options.vertexFunction(this._copy, this._vertex, i);
  56644. }
  56645. this._vertex.x *= this._copy.scaling.x;
  56646. this._vertex.y *= this._copy.scaling.y;
  56647. this._vertex.z *= this._copy.scaling.z;
  56648. this._vertex.x -= this._scaledPivot.x;
  56649. this._vertex.y -= this._scaledPivot.y;
  56650. this._vertex.z -= this._scaledPivot.z;
  56651. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56652. this._rotated.addInPlace(this._pivotBackTranslation);
  56653. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56654. if (meshUV) {
  56655. 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);
  56656. u += 2;
  56657. }
  56658. if (this._copy.color) {
  56659. this._color = this._copy.color;
  56660. }
  56661. else if (meshCol && meshCol[c] !== undefined) {
  56662. this._color.r = meshCol[c];
  56663. this._color.g = meshCol[c + 1];
  56664. this._color.b = meshCol[c + 2];
  56665. this._color.a = meshCol[c + 3];
  56666. }
  56667. else {
  56668. this._color.r = 1.0;
  56669. this._color.g = 1.0;
  56670. this._color.b = 1.0;
  56671. this._color.a = 1.0;
  56672. }
  56673. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56674. c += 4;
  56675. if (!this.recomputeNormals && meshNor) {
  56676. this._normal.x = meshNor[n];
  56677. this._normal.y = meshNor[n + 1];
  56678. this._normal.z = meshNor[n + 2];
  56679. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  56680. normals.push(this._normal.x, this._normal.y, this._normal.z);
  56681. n += 3;
  56682. }
  56683. }
  56684. for (i = 0; i < meshInd.length; i++) {
  56685. var current_ind = p + meshInd[i];
  56686. indices.push(current_ind);
  56687. if (current_ind > 65535) {
  56688. this._needs32Bits = true;
  56689. }
  56690. }
  56691. if (this._pickable) {
  56692. var nbfaces = meshInd.length / 3;
  56693. for (i = 0; i < nbfaces; i++) {
  56694. this.pickedParticles.push({ idx: idx, faceId: i });
  56695. }
  56696. }
  56697. if (this._depthSort) {
  56698. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  56699. }
  56700. return this._copy;
  56701. };
  56702. // returns a shape array from positions array
  56703. SolidParticleSystem.prototype._posToShape = function (positions) {
  56704. var shape = [];
  56705. for (var i = 0; i < positions.length; i += 3) {
  56706. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56707. }
  56708. return shape;
  56709. };
  56710. // returns a shapeUV array from a Vector4 uvs
  56711. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56712. var shapeUV = [];
  56713. if (uvs) {
  56714. for (var i = 0; i < uvs.length; i++)
  56715. shapeUV.push(uvs[i]);
  56716. }
  56717. return shapeUV;
  56718. };
  56719. // adds a new particle object in the particles array
  56720. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  56721. if (bInfo === void 0) { bInfo = null; }
  56722. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  56723. this.particles.push(sp);
  56724. return sp;
  56725. };
  56726. /**
  56727. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56728. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56729. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  56730. * @param nb (positive integer) the number of particles to be created from this model
  56731. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  56732. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  56733. * @returns the number of shapes in the system
  56734. */
  56735. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56737. var meshInd = mesh.getIndices();
  56738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56740. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56741. var bbInfo;
  56742. if (this._particlesIntersect) {
  56743. bbInfo = mesh.getBoundingInfo();
  56744. }
  56745. var shape = this._posToShape(meshPos);
  56746. var shapeUV = this._uvsToShapeUV(meshUV);
  56747. var posfunc = options ? options.positionFunction : null;
  56748. var vtxfunc = options ? options.vertexFunction : null;
  56749. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  56750. // particles
  56751. var sp;
  56752. var currentCopy;
  56753. var idx = this.nbParticles;
  56754. for (var i = 0; i < nb; i++) {
  56755. var currentPos = this._positions.length;
  56756. var currentInd = this._indices.length;
  56757. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  56758. if (this._updatable) {
  56759. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  56760. sp.position.copyFrom(currentCopy.position);
  56761. sp.rotation.copyFrom(currentCopy.rotation);
  56762. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  56763. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  56764. }
  56765. if (currentCopy.color && sp.color) {
  56766. sp.color.copyFrom(currentCopy.color);
  56767. }
  56768. sp.scaling.copyFrom(currentCopy.scaling);
  56769. sp.uvs.copyFrom(currentCopy.uvs);
  56770. }
  56771. this._index += shape.length;
  56772. idx++;
  56773. }
  56774. this.nbParticles += nb;
  56775. this._shapeCounter++;
  56776. return this._shapeCounter - 1;
  56777. };
  56778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56780. this._resetCopy();
  56781. if (particle._model._positionFunction) {
  56782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56783. }
  56784. if (this._copy.rotationQuaternion) {
  56785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56786. }
  56787. else {
  56788. this._yaw = this._copy.rotation.y;
  56789. this._pitch = this._copy.rotation.x;
  56790. this._roll = this._copy.rotation.z;
  56791. this._quaternionRotationYPR();
  56792. }
  56793. this._quaternionToRotationMatrix();
  56794. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  56795. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  56796. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  56797. if (this._copy.translateFromPivot) {
  56798. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56799. }
  56800. else {
  56801. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56802. }
  56803. this._shape = particle._model._shape;
  56804. for (var pt = 0; pt < this._shape.length; pt++) {
  56805. this._vertex.x = this._shape[pt].x;
  56806. this._vertex.y = this._shape[pt].y;
  56807. this._vertex.z = this._shape[pt].z;
  56808. if (particle._model._vertexFunction) {
  56809. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56810. }
  56811. this._vertex.x *= this._copy.scaling.x;
  56812. this._vertex.y *= this._copy.scaling.y;
  56813. this._vertex.z *= this._copy.scaling.z;
  56814. this._vertex.x -= this._scaledPivot.x;
  56815. this._vertex.y -= this._scaledPivot.y;
  56816. this._vertex.z -= this._scaledPivot.z;
  56817. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56818. this._rotated.addInPlace(this._pivotBackTranslation);
  56819. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56820. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56821. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56822. }
  56823. particle.position.x = 0.0;
  56824. particle.position.y = 0.0;
  56825. particle.position.z = 0.0;
  56826. particle.rotation.x = 0.0;
  56827. particle.rotation.y = 0.0;
  56828. particle.rotation.z = 0.0;
  56829. particle.rotationQuaternion = null;
  56830. particle.scaling.x = 1.0;
  56831. particle.scaling.y = 1.0;
  56832. particle.scaling.z = 1.0;
  56833. particle.uvs.x = 0.0;
  56834. particle.uvs.y = 0.0;
  56835. particle.uvs.z = 1.0;
  56836. particle.uvs.w = 1.0;
  56837. particle.pivot.x = 0.0;
  56838. particle.pivot.y = 0.0;
  56839. particle.pivot.z = 0.0;
  56840. particle.translateFromPivot = false;
  56841. particle.parentId = null;
  56842. };
  56843. /**
  56844. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56845. * @returns the SPS.
  56846. */
  56847. SolidParticleSystem.prototype.rebuildMesh = function () {
  56848. for (var p = 0; p < this.particles.length; p++) {
  56849. this._rebuildParticle(this.particles[p]);
  56850. }
  56851. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56852. return this;
  56853. };
  56854. /**
  56855. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56856. * This method calls `updateParticle()` for each particle of the SPS.
  56857. * For an animated SPS, it is usually called within the render loop.
  56858. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56859. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56860. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56861. * @returns the SPS.
  56862. */
  56863. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56864. if (start === void 0) { start = 0; }
  56865. if (end === void 0) { end = this.nbParticles - 1; }
  56866. if (update === void 0) { update = true; }
  56867. if (!this._updatable) {
  56868. return this;
  56869. }
  56870. // custom beforeUpdate
  56871. this.beforeUpdateParticles(start, end, update);
  56872. this._cam_axisX.x = 1.0;
  56873. this._cam_axisX.y = 0.0;
  56874. this._cam_axisX.z = 0.0;
  56875. this._cam_axisY.x = 0.0;
  56876. this._cam_axisY.y = 1.0;
  56877. this._cam_axisY.z = 0.0;
  56878. this._cam_axisZ.x = 0.0;
  56879. this._cam_axisZ.y = 0.0;
  56880. this._cam_axisZ.z = 1.0;
  56881. // cases when the World Matrix is to be computed first
  56882. if (this.billboard || this._depthSort) {
  56883. this.mesh.computeWorldMatrix(true);
  56884. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  56885. }
  56886. // if the particles will always face the camera
  56887. if (this.billboard) {
  56888. // compute the camera position and un-rotate it by the current mesh rotation
  56889. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  56890. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56891. this._cam_axisZ.normalize();
  56892. // same for camera up vector extracted from the cam view matrix
  56893. var view = this._camera.getViewMatrix(true);
  56894. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  56895. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56896. this._cam_axisY.normalize();
  56897. this._cam_axisX.normalize();
  56898. }
  56899. // if depthSort, compute the camera global position in the mesh local system
  56900. if (this._depthSort) {
  56901. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  56902. }
  56903. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56904. var idx = 0; // current position index in the global array positions32
  56905. var index = 0; // position start index in the global array positions32 of the current particle
  56906. var colidx = 0; // current color index in the global array colors32
  56907. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  56908. var uvidx = 0; // current uv index in the global array uvs32
  56909. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  56910. var pt = 0; // current index in the particle model shape
  56911. if (this.mesh.isFacetDataEnabled) {
  56912. this._computeBoundingBox = true;
  56913. }
  56914. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  56915. if (this._computeBoundingBox) {
  56916. if (start == 0 && end == this.nbParticles - 1) {
  56917. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56918. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56919. }
  56920. else {
  56921. if (this.mesh._boundingInfo) {
  56922. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  56923. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  56924. }
  56925. }
  56926. }
  56927. // particle loop
  56928. index = this.particles[start]._pos;
  56929. var vpos = (index / 3) | 0;
  56930. colorIndex = vpos * 4;
  56931. uvIndex = vpos * 2;
  56932. for (var p = start; p <= end; p++) {
  56933. this._particle = this.particles[p];
  56934. this._shape = this._particle._model._shape;
  56935. this._shapeUV = this._particle._model._shapeUV;
  56936. // call to custom user function to update the particle properties
  56937. this.updateParticle(this._particle);
  56938. // camera-particle distance for depth sorting
  56939. if (this._depthSort && this._depthSortParticles) {
  56940. var dsp = this.depthSortedParticles[p];
  56941. dsp.ind = this._particle._ind;
  56942. dsp.indicesLength = this._particle._model._indicesLength;
  56943. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  56944. }
  56945. // skip the computations for inactive or already invisible particles
  56946. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  56947. // increment indexes for the next particle
  56948. pt = this._shape.length;
  56949. index += pt * 3;
  56950. colorIndex += pt * 4;
  56951. uvIndex += pt * 2;
  56952. continue;
  56953. }
  56954. if (this._particle.isVisible) {
  56955. this._particle._stillInvisible = false; // un-mark permanent invisibility
  56956. this._particleHasParent = (this._particle.parentId !== null);
  56957. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  56958. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  56959. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  56960. // particle rotation matrix
  56961. if (this.billboard) {
  56962. this._particle.rotation.x = 0.0;
  56963. this._particle.rotation.y = 0.0;
  56964. }
  56965. if (this._computeParticleRotation || this.billboard) {
  56966. if (this._particle.rotationQuaternion) {
  56967. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56968. }
  56969. else {
  56970. this._yaw = this._particle.rotation.y;
  56971. this._pitch = this._particle.rotation.x;
  56972. this._roll = this._particle.rotation.z;
  56973. this._quaternionRotationYPR();
  56974. }
  56975. this._quaternionToRotationMatrix();
  56976. }
  56977. if (this._particleHasParent) {
  56978. this._parent = this.particles[this._particle.parentId];
  56979. 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];
  56980. 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];
  56981. 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];
  56982. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  56983. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  56984. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  56985. if (this._computeParticleRotation || this.billboard) {
  56986. 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];
  56987. 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];
  56988. 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];
  56989. 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];
  56990. 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];
  56991. 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];
  56992. 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];
  56993. 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];
  56994. 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];
  56995. }
  56996. }
  56997. else {
  56998. this._particle._globalPosition.x = this._particle.position.x;
  56999. this._particle._globalPosition.y = this._particle.position.y;
  57000. this._particle._globalPosition.z = this._particle.position.z;
  57001. if (this._computeParticleRotation || this.billboard) {
  57002. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57003. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57004. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57005. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57006. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57007. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57008. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57009. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57010. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57011. }
  57012. }
  57013. if (this._particle.translateFromPivot) {
  57014. this._pivotBackTranslation.x = 0.0;
  57015. this._pivotBackTranslation.y = 0.0;
  57016. this._pivotBackTranslation.z = 0.0;
  57017. }
  57018. else {
  57019. this._pivotBackTranslation.x = this._scaledPivot.x;
  57020. this._pivotBackTranslation.y = this._scaledPivot.y;
  57021. this._pivotBackTranslation.z = this._scaledPivot.z;
  57022. }
  57023. // particle vertex loop
  57024. for (pt = 0; pt < this._shape.length; pt++) {
  57025. idx = index + pt * 3;
  57026. colidx = colorIndex + pt * 4;
  57027. uvidx = uvIndex + pt * 2;
  57028. this._vertex.x = this._shape[pt].x;
  57029. this._vertex.y = this._shape[pt].y;
  57030. this._vertex.z = this._shape[pt].z;
  57031. if (this._computeParticleVertex) {
  57032. this.updateParticleVertex(this._particle, this._vertex, pt);
  57033. }
  57034. // positions
  57035. this._vertex.x *= this._particle.scaling.x;
  57036. this._vertex.y *= this._particle.scaling.y;
  57037. this._vertex.z *= this._particle.scaling.z;
  57038. this._vertex.x -= this._scaledPivot.x;
  57039. this._vertex.y -= this._scaledPivot.y;
  57040. this._vertex.z -= this._scaledPivot.z;
  57041. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57042. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57043. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57044. this._rotated.x += this._pivotBackTranslation.x;
  57045. this._rotated.y += this._pivotBackTranslation.y;
  57046. this._rotated.z += this._pivotBackTranslation.z;
  57047. 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;
  57048. 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;
  57049. 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;
  57050. if (this._computeBoundingBox) {
  57051. if (this._positions32[idx] < this._minimum.x) {
  57052. this._minimum.x = this._positions32[idx];
  57053. }
  57054. if (this._positions32[idx] > this._maximum.x) {
  57055. this._maximum.x = this._positions32[idx];
  57056. }
  57057. if (this._positions32[idx + 1] < this._minimum.y) {
  57058. this._minimum.y = this._positions32[idx + 1];
  57059. }
  57060. if (this._positions32[idx + 1] > this._maximum.y) {
  57061. this._maximum.y = this._positions32[idx + 1];
  57062. }
  57063. if (this._positions32[idx + 2] < this._minimum.z) {
  57064. this._minimum.z = this._positions32[idx + 2];
  57065. }
  57066. if (this._positions32[idx + 2] > this._maximum.z) {
  57067. this._maximum.z = this._positions32[idx + 2];
  57068. }
  57069. }
  57070. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57071. if (!this._computeParticleVertex) {
  57072. this._normal.x = this._fixedNormal32[idx];
  57073. this._normal.y = this._fixedNormal32[idx + 1];
  57074. this._normal.z = this._fixedNormal32[idx + 2];
  57075. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57076. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57077. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57078. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57079. 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;
  57080. 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;
  57081. }
  57082. if (this._computeParticleColor && this._particle.color) {
  57083. this._colors32[colidx] = this._particle.color.r;
  57084. this._colors32[colidx + 1] = this._particle.color.g;
  57085. this._colors32[colidx + 2] = this._particle.color.b;
  57086. this._colors32[colidx + 3] = this._particle.color.a;
  57087. }
  57088. if (this._computeParticleTexture) {
  57089. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57090. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57091. }
  57092. }
  57093. }
  57094. else {
  57095. this._particle._stillInvisible = true; // mark the particle as invisible
  57096. for (pt = 0; pt < this._shape.length; pt++) {
  57097. idx = index + pt * 3;
  57098. colidx = colorIndex + pt * 4;
  57099. uvidx = uvIndex + pt * 2;
  57100. this._positions32[idx] = 0.0;
  57101. this._positions32[idx + 1] = 0.0;
  57102. this._positions32[idx + 2] = 0.0;
  57103. this._normals32[idx] = 0.0;
  57104. this._normals32[idx + 1] = 0.0;
  57105. this._normals32[idx + 2] = 0.0;
  57106. if (this._computeParticleColor && this._particle.color) {
  57107. this._colors32[colidx] = this._particle.color.r;
  57108. this._colors32[colidx + 1] = this._particle.color.g;
  57109. this._colors32[colidx + 2] = this._particle.color.b;
  57110. this._colors32[colidx + 3] = this._particle.color.a;
  57111. }
  57112. if (this._computeParticleTexture) {
  57113. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57114. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57115. }
  57116. }
  57117. }
  57118. // if the particle intersections must be computed : update the bbInfo
  57119. if (this._particlesIntersect) {
  57120. var bInfo = this._particle._boundingInfo;
  57121. var bBox = bInfo.boundingBox;
  57122. var bSphere = bInfo.boundingSphere;
  57123. if (!this._bSphereOnly) {
  57124. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57125. for (var b = 0; b < bBox.vectors.length; b++) {
  57126. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57127. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57128. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57129. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57130. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57131. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57132. 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;
  57133. 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;
  57134. 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;
  57135. }
  57136. bBox._update(this.mesh._worldMatrix);
  57137. }
  57138. // place and scale the particle bouding sphere in the SPS local system, then update it
  57139. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57140. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57141. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57142. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57143. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57144. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57145. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57146. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57147. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57148. 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));
  57149. bSphere._update(this.mesh._worldMatrix);
  57150. }
  57151. // increment indexes for the next particle
  57152. index = idx + 3;
  57153. colorIndex = colidx + 4;
  57154. uvIndex = uvidx + 2;
  57155. }
  57156. // if the VBO must be updated
  57157. if (update) {
  57158. if (this._computeParticleColor) {
  57159. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57160. }
  57161. if (this._computeParticleTexture) {
  57162. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57163. }
  57164. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57165. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57166. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57167. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57168. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57169. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57170. for (var i = 0; i < this._normals32.length; i++) {
  57171. this._fixedNormal32[i] = this._normals32[i];
  57172. }
  57173. }
  57174. if (!this.mesh.areNormalsFrozen) {
  57175. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57176. }
  57177. }
  57178. if (this._depthSort && this._depthSortParticles) {
  57179. this.depthSortedParticles.sort(this._depthSortFunction);
  57180. var dspl = this.depthSortedParticles.length;
  57181. var sorted = 0;
  57182. var lind = 0;
  57183. var sind = 0;
  57184. var sid = 0;
  57185. for (sorted = 0; sorted < dspl; sorted++) {
  57186. lind = this.depthSortedParticles[sorted].indicesLength;
  57187. sind = this.depthSortedParticles[sorted].ind;
  57188. for (var i = 0; i < lind; i++) {
  57189. this._indices32[sid] = this._indices[sind + i];
  57190. sid++;
  57191. }
  57192. }
  57193. this.mesh.updateIndices(this._indices32);
  57194. }
  57195. }
  57196. if (this._computeBoundingBox) {
  57197. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57198. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57199. }
  57200. this.afterUpdateParticles(start, end, update);
  57201. return this;
  57202. };
  57203. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57204. this._halfroll = this._roll * 0.5;
  57205. this._halfpitch = this._pitch * 0.5;
  57206. this._halfyaw = this._yaw * 0.5;
  57207. this._sinRoll = Math.sin(this._halfroll);
  57208. this._cosRoll = Math.cos(this._halfroll);
  57209. this._sinPitch = Math.sin(this._halfpitch);
  57210. this._cosPitch = Math.cos(this._halfpitch);
  57211. this._sinYaw = Math.sin(this._halfyaw);
  57212. this._cosYaw = Math.cos(this._halfyaw);
  57213. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57214. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57215. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57216. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57217. };
  57218. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57219. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57220. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57221. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57222. this._rotMatrix.m[3] = 0;
  57223. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57224. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57225. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57226. this._rotMatrix.m[7] = 0;
  57227. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57228. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57229. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57230. this._rotMatrix.m[11] = 0;
  57231. this._rotMatrix.m[12] = 0;
  57232. this._rotMatrix.m[13] = 0;
  57233. this._rotMatrix.m[14] = 0;
  57234. this._rotMatrix.m[15] = 1.0;
  57235. };
  57236. /**
  57237. * Disposes the SPS.
  57238. */
  57239. SolidParticleSystem.prototype.dispose = function () {
  57240. this.mesh.dispose();
  57241. this.vars = null;
  57242. // drop references to internal big arrays for the GC
  57243. this._positions = null;
  57244. this._indices = null;
  57245. this._normals = null;
  57246. this._uvs = null;
  57247. this._colors = null;
  57248. this._indices32 = null;
  57249. this._positions32 = null;
  57250. this._normals32 = null;
  57251. this._fixedNormal32 = null;
  57252. this._uvs32 = null;
  57253. this._colors32 = null;
  57254. this.pickedParticles = null;
  57255. };
  57256. /**
  57257. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57258. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57259. * @returns the SPS.
  57260. */
  57261. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57262. if (!this._isVisibilityBoxLocked) {
  57263. this.mesh.refreshBoundingInfo();
  57264. }
  57265. return this;
  57266. };
  57267. /**
  57268. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57269. * @param size the size (float) of the visibility box
  57270. * note : this doesn't lock the SPS mesh bounding box.
  57271. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57272. */
  57273. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57274. var vis = size / 2;
  57275. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57276. };
  57277. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57278. /**
  57279. * Gets whether the SPS as always visible or not
  57280. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57281. */
  57282. get: function () {
  57283. return this._alwaysVisible;
  57284. },
  57285. /**
  57286. * Sets the SPS as always visible or not
  57287. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57288. */
  57289. set: function (val) {
  57290. this._alwaysVisible = val;
  57291. this.mesh.alwaysSelectAsActiveMesh = val;
  57292. },
  57293. enumerable: true,
  57294. configurable: true
  57295. });
  57296. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57297. /**
  57298. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57300. */
  57301. get: function () {
  57302. return this._isVisibilityBoxLocked;
  57303. },
  57304. /**
  57305. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57306. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57307. */
  57308. set: function (val) {
  57309. this._isVisibilityBoxLocked = val;
  57310. var boundingInfo = this.mesh.getBoundingInfo();
  57311. boundingInfo.isLocked = val;
  57312. },
  57313. enumerable: true,
  57314. configurable: true
  57315. });
  57316. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57317. /**
  57318. * Gets if `setParticles()` computes the particle rotations or not.
  57319. * Default value : true. The SPS is faster when it's set to false.
  57320. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57321. */
  57322. get: function () {
  57323. return this._computeParticleRotation;
  57324. },
  57325. /**
  57326. * Tells to `setParticles()` to compute the particle rotations or not.
  57327. * Default value : true. The SPS is faster when it's set to false.
  57328. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57329. */
  57330. set: function (val) {
  57331. this._computeParticleRotation = val;
  57332. },
  57333. enumerable: true,
  57334. configurable: true
  57335. });
  57336. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57337. /**
  57338. * Gets if `setParticles()` computes the particle colors or not.
  57339. * Default value : true. The SPS is faster when it's set to false.
  57340. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57341. */
  57342. get: function () {
  57343. return this._computeParticleColor;
  57344. },
  57345. /**
  57346. * Tells to `setParticles()` to compute the particle colors or not.
  57347. * Default value : true. The SPS is faster when it's set to false.
  57348. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57349. */
  57350. set: function (val) {
  57351. this._computeParticleColor = val;
  57352. },
  57353. enumerable: true,
  57354. configurable: true
  57355. });
  57356. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57357. /**
  57358. * Gets if `setParticles()` computes the particle textures or not.
  57359. * Default value : true. The SPS is faster when it's set to false.
  57360. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57361. */
  57362. get: function () {
  57363. return this._computeParticleTexture;
  57364. },
  57365. set: function (val) {
  57366. this._computeParticleTexture = val;
  57367. },
  57368. enumerable: true,
  57369. configurable: true
  57370. });
  57371. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57372. /**
  57373. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57374. * Default value : false. The SPS is faster when it's set to false.
  57375. * Note : the particle custom vertex positions aren't stored values.
  57376. */
  57377. get: function () {
  57378. return this._computeParticleVertex;
  57379. },
  57380. /**
  57381. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57382. * Default value : false. The SPS is faster when it's set to false.
  57383. * Note : the particle custom vertex positions aren't stored values.
  57384. */
  57385. set: function (val) {
  57386. this._computeParticleVertex = val;
  57387. },
  57388. enumerable: true,
  57389. configurable: true
  57390. });
  57391. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57392. /**
  57393. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  57394. */
  57395. get: function () {
  57396. return this._computeBoundingBox;
  57397. },
  57398. /**
  57399. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57400. */
  57401. set: function (val) {
  57402. this._computeBoundingBox = val;
  57403. },
  57404. enumerable: true,
  57405. configurable: true
  57406. });
  57407. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  57408. /**
  57409. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  57410. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57411. * Default : `true`
  57412. */
  57413. get: function () {
  57414. return this._depthSortParticles;
  57415. },
  57416. /**
  57417. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  57418. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57419. * Default : `true`
  57420. */
  57421. set: function (val) {
  57422. this._depthSortParticles = val;
  57423. },
  57424. enumerable: true,
  57425. configurable: true
  57426. });
  57427. // =======================================================================
  57428. // Particle behavior logic
  57429. // these following methods may be overwritten by the user to fit his needs
  57430. /**
  57431. * This function does nothing. It may be overwritten to set all the particle first values.
  57432. * The SPS doesn't call this function, you may have to call it by your own.
  57433. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57434. */
  57435. SolidParticleSystem.prototype.initParticles = function () {
  57436. };
  57437. /**
  57438. * This function does nothing. It may be overwritten to recycle a particle.
  57439. * The SPS doesn't call this function, you may have to call it by your own.
  57440. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57441. * @param particle The particle to recycle
  57442. * @returns the recycled particle
  57443. */
  57444. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57445. return particle;
  57446. };
  57447. /**
  57448. * Updates a particle : this function should be overwritten by the user.
  57449. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57450. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57451. * @example : just set a particle position or velocity and recycle conditions
  57452. * @param particle The particle to update
  57453. * @returns the updated particle
  57454. */
  57455. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57456. return particle;
  57457. };
  57458. /**
  57459. * Updates a vertex of a particle : it can be overwritten by the user.
  57460. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57461. * @param particle the current particle
  57462. * @param vertex the current index of the current particle
  57463. * @param pt the index of the current vertex in the particle shape
  57464. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57465. * @example : just set a vertex particle position
  57466. * @returns the updated vertex
  57467. */
  57468. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57469. return vertex;
  57470. };
  57471. /**
  57472. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57473. * This does nothing and may be overwritten by the user.
  57474. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57475. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57476. * @param update the boolean update value actually passed to setParticles()
  57477. */
  57478. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57479. };
  57480. /**
  57481. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57482. * This will be passed three parameters.
  57483. * This does nothing and may be overwritten by the user.
  57484. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57485. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57486. * @param update the boolean update value actually passed to setParticles()
  57487. */
  57488. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57489. };
  57490. return SolidParticleSystem;
  57491. }());
  57492. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57493. })(BABYLON || (BABYLON = {}));
  57494. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  57495. "use strict";
  57496. var BABYLON;
  57497. (function (BABYLON) {
  57498. var ShaderMaterial = /** @class */ (function (_super) {
  57499. __extends(ShaderMaterial, _super);
  57500. function ShaderMaterial(name, scene, shaderPath, options) {
  57501. var _this = _super.call(this, name, scene) || this;
  57502. _this._textures = {};
  57503. _this._textureArrays = {};
  57504. _this._floats = {};
  57505. _this._ints = {};
  57506. _this._floatsArrays = {};
  57507. _this._colors3 = {};
  57508. _this._colors3Arrays = {};
  57509. _this._colors4 = {};
  57510. _this._vectors2 = {};
  57511. _this._vectors3 = {};
  57512. _this._vectors4 = {};
  57513. _this._matrices = {};
  57514. _this._matrices3x3 = {};
  57515. _this._matrices2x2 = {};
  57516. _this._vectors2Arrays = {};
  57517. _this._vectors3Arrays = {};
  57518. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57519. _this._shaderPath = shaderPath;
  57520. options.needAlphaBlending = options.needAlphaBlending || false;
  57521. options.needAlphaTesting = options.needAlphaTesting || false;
  57522. options.attributes = options.attributes || ["position", "normal", "uv"];
  57523. options.uniforms = options.uniforms || ["worldViewProjection"];
  57524. options.uniformBuffers = options.uniformBuffers || [];
  57525. options.samplers = options.samplers || [];
  57526. options.defines = options.defines || [];
  57527. _this._options = options;
  57528. return _this;
  57529. }
  57530. ShaderMaterial.prototype.getClassName = function () {
  57531. return "ShaderMaterial";
  57532. };
  57533. ShaderMaterial.prototype.needAlphaBlending = function () {
  57534. return this._options.needAlphaBlending;
  57535. };
  57536. ShaderMaterial.prototype.needAlphaTesting = function () {
  57537. return this._options.needAlphaTesting;
  57538. };
  57539. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57540. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57541. this._options.uniforms.push(uniformName);
  57542. }
  57543. };
  57544. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57545. if (this._options.samplers.indexOf(name) === -1) {
  57546. this._options.samplers.push(name);
  57547. }
  57548. this._textures[name] = texture;
  57549. return this;
  57550. };
  57551. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57552. if (this._options.samplers.indexOf(name) === -1) {
  57553. this._options.samplers.push(name);
  57554. }
  57555. this._checkUniform(name);
  57556. this._textureArrays[name] = textures;
  57557. return this;
  57558. };
  57559. ShaderMaterial.prototype.setFloat = function (name, value) {
  57560. this._checkUniform(name);
  57561. this._floats[name] = value;
  57562. return this;
  57563. };
  57564. ShaderMaterial.prototype.setInt = function (name, value) {
  57565. this._checkUniform(name);
  57566. this._ints[name] = value;
  57567. return this;
  57568. };
  57569. ShaderMaterial.prototype.setFloats = function (name, value) {
  57570. this._checkUniform(name);
  57571. this._floatsArrays[name] = value;
  57572. return this;
  57573. };
  57574. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57575. this._checkUniform(name);
  57576. this._colors3[name] = value;
  57577. return this;
  57578. };
  57579. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57580. this._checkUniform(name);
  57581. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57582. color.toArray(arr, arr.length);
  57583. return arr;
  57584. }, []);
  57585. return this;
  57586. };
  57587. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57588. this._checkUniform(name);
  57589. this._colors4[name] = value;
  57590. return this;
  57591. };
  57592. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57593. this._checkUniform(name);
  57594. this._vectors2[name] = value;
  57595. return this;
  57596. };
  57597. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57598. this._checkUniform(name);
  57599. this._vectors3[name] = value;
  57600. return this;
  57601. };
  57602. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57603. this._checkUniform(name);
  57604. this._vectors4[name] = value;
  57605. return this;
  57606. };
  57607. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57608. this._checkUniform(name);
  57609. this._matrices[name] = value;
  57610. return this;
  57611. };
  57612. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57613. this._checkUniform(name);
  57614. this._matrices3x3[name] = value;
  57615. return this;
  57616. };
  57617. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57618. this._checkUniform(name);
  57619. this._matrices2x2[name] = value;
  57620. return this;
  57621. };
  57622. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57623. this._checkUniform(name);
  57624. this._vectors2Arrays[name] = value;
  57625. return this;
  57626. };
  57627. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57628. this._checkUniform(name);
  57629. this._vectors3Arrays[name] = value;
  57630. return this;
  57631. };
  57632. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57633. if (!mesh) {
  57634. return true;
  57635. }
  57636. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57637. return false;
  57638. }
  57639. return false;
  57640. };
  57641. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57642. var scene = this.getScene();
  57643. var engine = scene.getEngine();
  57644. if (!this.checkReadyOnEveryCall) {
  57645. if (this._renderId === scene.getRenderId()) {
  57646. if (this._checkCache(scene, mesh, useInstances)) {
  57647. return true;
  57648. }
  57649. }
  57650. }
  57651. // Instances
  57652. var defines = [];
  57653. var attribs = [];
  57654. var fallbacks = new BABYLON.EffectFallbacks();
  57655. if (useInstances) {
  57656. defines.push("#define INSTANCES");
  57657. }
  57658. for (var index = 0; index < this._options.defines.length; index++) {
  57659. defines.push(this._options.defines[index]);
  57660. }
  57661. for (var index = 0; index < this._options.attributes.length; index++) {
  57662. attribs.push(this._options.attributes[index]);
  57663. }
  57664. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57665. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57666. defines.push("#define VERTEXCOLOR");
  57667. }
  57668. // Bones
  57669. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57672. if (mesh.numBoneInfluencers > 4) {
  57673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57675. }
  57676. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57677. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57678. fallbacks.addCPUSkinningFallback(0, mesh);
  57679. if (this._options.uniforms.indexOf("mBones") === -1) {
  57680. this._options.uniforms.push("mBones");
  57681. }
  57682. }
  57683. else {
  57684. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57685. }
  57686. // Textures
  57687. for (var name in this._textures) {
  57688. if (!this._textures[name].isReady()) {
  57689. return false;
  57690. }
  57691. }
  57692. // Alpha test
  57693. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57694. defines.push("#define ALPHATEST");
  57695. }
  57696. var previousEffect = this._effect;
  57697. var join = defines.join("\n");
  57698. this._effect = engine.createEffect(this._shaderPath, {
  57699. attributes: attribs,
  57700. uniformsNames: this._options.uniforms,
  57701. uniformBuffersNames: this._options.uniformBuffers,
  57702. samplers: this._options.samplers,
  57703. defines: join,
  57704. fallbacks: fallbacks,
  57705. onCompiled: this.onCompiled,
  57706. onError: this.onError
  57707. }, engine);
  57708. if (!this._effect.isReady()) {
  57709. return false;
  57710. }
  57711. if (previousEffect !== this._effect) {
  57712. scene.resetCachedMaterial();
  57713. }
  57714. this._renderId = scene.getRenderId();
  57715. return true;
  57716. };
  57717. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57718. var scene = this.getScene();
  57719. if (!this._effect) {
  57720. return;
  57721. }
  57722. if (this._options.uniforms.indexOf("world") !== -1) {
  57723. this._effect.setMatrix("world", world);
  57724. }
  57725. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57726. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57727. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57728. }
  57729. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57730. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57731. }
  57732. };
  57733. ShaderMaterial.prototype.bind = function (world, mesh) {
  57734. // Std values
  57735. this.bindOnlyWorldMatrix(world);
  57736. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57737. if (this._options.uniforms.indexOf("view") !== -1) {
  57738. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57739. }
  57740. if (this._options.uniforms.indexOf("projection") !== -1) {
  57741. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57742. }
  57743. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57744. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57745. }
  57746. // Bones
  57747. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57748. var name;
  57749. // Texture
  57750. for (name in this._textures) {
  57751. this._effect.setTexture(name, this._textures[name]);
  57752. }
  57753. // Texture arrays
  57754. for (name in this._textureArrays) {
  57755. this._effect.setTextureArray(name, this._textureArrays[name]);
  57756. }
  57757. // Int
  57758. for (name in this._ints) {
  57759. this._effect.setInt(name, this._ints[name]);
  57760. }
  57761. // Float
  57762. for (name in this._floats) {
  57763. this._effect.setFloat(name, this._floats[name]);
  57764. }
  57765. // Floats
  57766. for (name in this._floatsArrays) {
  57767. this._effect.setArray(name, this._floatsArrays[name]);
  57768. }
  57769. // Color3
  57770. for (name in this._colors3) {
  57771. this._effect.setColor3(name, this._colors3[name]);
  57772. }
  57773. for (name in this._colors3Arrays) {
  57774. this._effect.setArray3(name, this._colors3Arrays[name]);
  57775. }
  57776. // Color4
  57777. for (name in this._colors4) {
  57778. var color = this._colors4[name];
  57779. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57780. }
  57781. // Vector2
  57782. for (name in this._vectors2) {
  57783. this._effect.setVector2(name, this._vectors2[name]);
  57784. }
  57785. // Vector3
  57786. for (name in this._vectors3) {
  57787. this._effect.setVector3(name, this._vectors3[name]);
  57788. }
  57789. // Vector4
  57790. for (name in this._vectors4) {
  57791. this._effect.setVector4(name, this._vectors4[name]);
  57792. }
  57793. // Matrix
  57794. for (name in this._matrices) {
  57795. this._effect.setMatrix(name, this._matrices[name]);
  57796. }
  57797. // Matrix 3x3
  57798. for (name in this._matrices3x3) {
  57799. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57800. }
  57801. // Matrix 2x2
  57802. for (name in this._matrices2x2) {
  57803. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57804. }
  57805. // Vector2Array
  57806. for (name in this._vectors2Arrays) {
  57807. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57808. }
  57809. // Vector3Array
  57810. for (name in this._vectors3Arrays) {
  57811. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57812. }
  57813. }
  57814. this._afterBind(mesh);
  57815. };
  57816. ShaderMaterial.prototype.getActiveTextures = function () {
  57817. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57818. for (var name in this._textures) {
  57819. activeTextures.push(this._textures[name]);
  57820. }
  57821. for (var name in this._textureArrays) {
  57822. var array = this._textureArrays[name];
  57823. for (var index = 0; index < array.length; index++) {
  57824. activeTextures.push(array[index]);
  57825. }
  57826. }
  57827. return activeTextures;
  57828. };
  57829. ShaderMaterial.prototype.hasTexture = function (texture) {
  57830. if (_super.prototype.hasTexture.call(this, texture)) {
  57831. return true;
  57832. }
  57833. for (var name in this._textures) {
  57834. if (this._textures[name] === texture) {
  57835. return true;
  57836. }
  57837. }
  57838. for (var name in this._textureArrays) {
  57839. var array = this._textureArrays[name];
  57840. for (var index = 0; index < array.length; index++) {
  57841. if (array[index] === texture) {
  57842. return true;
  57843. }
  57844. }
  57845. }
  57846. return false;
  57847. };
  57848. ShaderMaterial.prototype.clone = function (name) {
  57849. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57850. return newShaderMaterial;
  57851. };
  57852. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57853. if (forceDisposeTextures) {
  57854. var name;
  57855. for (name in this._textures) {
  57856. this._textures[name].dispose();
  57857. }
  57858. for (name in this._textureArrays) {
  57859. var array = this._textureArrays[name];
  57860. for (var index = 0; index < array.length; index++) {
  57861. array[index].dispose();
  57862. }
  57863. }
  57864. }
  57865. this._textures = {};
  57866. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57867. };
  57868. ShaderMaterial.prototype.serialize = function () {
  57869. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57870. serializationObject.customType = "BABYLON.ShaderMaterial";
  57871. serializationObject.options = this._options;
  57872. serializationObject.shaderPath = this._shaderPath;
  57873. var name;
  57874. // Texture
  57875. serializationObject.textures = {};
  57876. for (name in this._textures) {
  57877. serializationObject.textures[name] = this._textures[name].serialize();
  57878. }
  57879. // Texture arrays
  57880. serializationObject.textureArrays = {};
  57881. for (name in this._textureArrays) {
  57882. serializationObject.textureArrays[name] = [];
  57883. var array = this._textureArrays[name];
  57884. for (var index = 0; index < array.length; index++) {
  57885. serializationObject.textureArrays[name].push(array[index].serialize());
  57886. }
  57887. }
  57888. // Float
  57889. serializationObject.floats = {};
  57890. for (name in this._floats) {
  57891. serializationObject.floats[name] = this._floats[name];
  57892. }
  57893. // Float s
  57894. serializationObject.FloatArrays = {};
  57895. for (name in this._floatsArrays) {
  57896. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57897. }
  57898. // Color3
  57899. serializationObject.colors3 = {};
  57900. for (name in this._colors3) {
  57901. serializationObject.colors3[name] = this._colors3[name].asArray();
  57902. }
  57903. // Color3 array
  57904. serializationObject.colors3Arrays = {};
  57905. for (name in this._colors3Arrays) {
  57906. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57907. }
  57908. // Color4
  57909. serializationObject.colors4 = {};
  57910. for (name in this._colors4) {
  57911. serializationObject.colors4[name] = this._colors4[name].asArray();
  57912. }
  57913. // Vector2
  57914. serializationObject.vectors2 = {};
  57915. for (name in this._vectors2) {
  57916. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57917. }
  57918. // Vector3
  57919. serializationObject.vectors3 = {};
  57920. for (name in this._vectors3) {
  57921. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57922. }
  57923. // Vector4
  57924. serializationObject.vectors4 = {};
  57925. for (name in this._vectors4) {
  57926. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57927. }
  57928. // Matrix
  57929. serializationObject.matrices = {};
  57930. for (name in this._matrices) {
  57931. serializationObject.matrices[name] = this._matrices[name].asArray();
  57932. }
  57933. // Matrix 3x3
  57934. serializationObject.matrices3x3 = {};
  57935. for (name in this._matrices3x3) {
  57936. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57937. }
  57938. // Matrix 2x2
  57939. serializationObject.matrices2x2 = {};
  57940. for (name in this._matrices2x2) {
  57941. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57942. }
  57943. // Vector2Array
  57944. serializationObject.vectors2Arrays = {};
  57945. for (name in this._vectors2Arrays) {
  57946. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57947. }
  57948. // Vector3Array
  57949. serializationObject.vectors3Arrays = {};
  57950. for (name in this._vectors3Arrays) {
  57951. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57952. }
  57953. return serializationObject;
  57954. };
  57955. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57956. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57957. var name;
  57958. // Texture
  57959. for (name in source.textures) {
  57960. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57961. }
  57962. // Texture arrays
  57963. for (name in source.textureArrays) {
  57964. var array = source.textureArrays[name];
  57965. var textureArray = new Array();
  57966. for (var index = 0; index < array.length; index++) {
  57967. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57968. }
  57969. material.setTextureArray(name, textureArray);
  57970. }
  57971. // Float
  57972. for (name in source.floats) {
  57973. material.setFloat(name, source.floats[name]);
  57974. }
  57975. // Float s
  57976. for (name in source.floatsArrays) {
  57977. material.setFloats(name, source.floatsArrays[name]);
  57978. }
  57979. // Color3
  57980. for (name in source.colors3) {
  57981. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57982. }
  57983. // Color3 arrays
  57984. for (name in source.colors3Arrays) {
  57985. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57986. if (i % 3 === 0) {
  57987. arr.push([num]);
  57988. }
  57989. else {
  57990. arr[arr.length - 1].push(num);
  57991. }
  57992. return arr;
  57993. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57994. material.setColor3Array(name, colors);
  57995. }
  57996. // Color4
  57997. for (name in source.colors4) {
  57998. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57999. }
  58000. // Vector2
  58001. for (name in source.vectors2) {
  58002. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58003. }
  58004. // Vector3
  58005. for (name in source.vectors3) {
  58006. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58007. }
  58008. // Vector4
  58009. for (name in source.vectors4) {
  58010. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58011. }
  58012. // Matrix
  58013. for (name in source.matrices) {
  58014. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58015. }
  58016. // Matrix 3x3
  58017. for (name in source.matrices3x3) {
  58018. material.setMatrix3x3(name, source.matrices3x3[name]);
  58019. }
  58020. // Matrix 2x2
  58021. for (name in source.matrices2x2) {
  58022. material.setMatrix2x2(name, source.matrices2x2[name]);
  58023. }
  58024. // Vector2Array
  58025. for (name in source.vectors2Arrays) {
  58026. material.setArray2(name, source.vectors2Arrays[name]);
  58027. }
  58028. // Vector3Array
  58029. for (name in source.vectors3Arrays) {
  58030. material.setArray3(name, source.vectors3Arrays[name]);
  58031. }
  58032. return material;
  58033. };
  58034. return ShaderMaterial;
  58035. }(BABYLON.Material));
  58036. BABYLON.ShaderMaterial = ShaderMaterial;
  58037. })(BABYLON || (BABYLON = {}));
  58038. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58039. "use strict";
  58040. var BABYLON;
  58041. (function (BABYLON) {
  58042. var GroundMesh = /** @class */ (function (_super) {
  58043. __extends(GroundMesh, _super);
  58044. function GroundMesh(name, scene) {
  58045. var _this = _super.call(this, name, scene) || this;
  58046. _this.generateOctree = false;
  58047. return _this;
  58048. }
  58049. GroundMesh.prototype.getClassName = function () {
  58050. return "GroundMesh";
  58051. };
  58052. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58053. get: function () {
  58054. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58055. },
  58056. enumerable: true,
  58057. configurable: true
  58058. });
  58059. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58060. get: function () {
  58061. return this._subdivisionsX;
  58062. },
  58063. enumerable: true,
  58064. configurable: true
  58065. });
  58066. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58067. get: function () {
  58068. return this._subdivisionsY;
  58069. },
  58070. enumerable: true,
  58071. configurable: true
  58072. });
  58073. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58074. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58075. this._subdivisionsX = chunksCount;
  58076. this._subdivisionsY = chunksCount;
  58077. this.subdivide(chunksCount);
  58078. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58079. };
  58080. /**
  58081. * Returns a height (y) value in the Worl system :
  58082. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58083. * Returns the ground y position if (x, z) are outside the ground surface.
  58084. */
  58085. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58086. var world = this.getWorldMatrix();
  58087. var invMat = BABYLON.Tmp.Matrix[5];
  58088. world.invertToRef(invMat);
  58089. var tmpVect = BABYLON.Tmp.Vector3[8];
  58090. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58091. x = tmpVect.x;
  58092. z = tmpVect.z;
  58093. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58094. return this.position.y;
  58095. }
  58096. if (!this._heightQuads || this._heightQuads.length == 0) {
  58097. this._initHeightQuads();
  58098. this._computeHeightQuads();
  58099. }
  58100. var facet = this._getFacetAt(x, z);
  58101. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58102. // return y in the World system
  58103. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58104. return tmpVect.y;
  58105. };
  58106. /**
  58107. * Returns a normalized vector (Vector3) orthogonal to the ground
  58108. * at the ground coordinates (x, z) expressed in the World system.
  58109. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58110. */
  58111. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58112. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58113. this.getNormalAtCoordinatesToRef(x, z, normal);
  58114. return normal;
  58115. };
  58116. /**
  58117. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58118. * at the ground coordinates (x, z) expressed in the World system.
  58119. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58120. * Returns the GroundMesh.
  58121. */
  58122. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58123. var world = this.getWorldMatrix();
  58124. var tmpMat = BABYLON.Tmp.Matrix[5];
  58125. world.invertToRef(tmpMat);
  58126. var tmpVect = BABYLON.Tmp.Vector3[8];
  58127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58128. x = tmpVect.x;
  58129. z = tmpVect.z;
  58130. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58131. return this;
  58132. }
  58133. if (!this._heightQuads || this._heightQuads.length == 0) {
  58134. this._initHeightQuads();
  58135. this._computeHeightQuads();
  58136. }
  58137. var facet = this._getFacetAt(x, z);
  58138. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58139. return this;
  58140. };
  58141. /**
  58142. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58143. * if the ground has been updated.
  58144. * This can be used in the render loop.
  58145. * Returns the GroundMesh.
  58146. */
  58147. GroundMesh.prototype.updateCoordinateHeights = function () {
  58148. if (!this._heightQuads || this._heightQuads.length == 0) {
  58149. this._initHeightQuads();
  58150. }
  58151. this._computeHeightQuads();
  58152. return this;
  58153. };
  58154. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58155. GroundMesh.prototype._getFacetAt = function (x, z) {
  58156. // retrieve col and row from x, z coordinates in the ground local system
  58157. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58158. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58159. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58160. var facet;
  58161. if (z < quad.slope.x * x + quad.slope.y) {
  58162. facet = quad.facet1;
  58163. }
  58164. else {
  58165. facet = quad.facet2;
  58166. }
  58167. return facet;
  58168. };
  58169. // Creates and populates the heightMap array with "facet" elements :
  58170. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58171. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58172. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58173. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58174. // Returns the GroundMesh.
  58175. GroundMesh.prototype._initHeightQuads = function () {
  58176. var subdivisionsX = this._subdivisionsX;
  58177. var subdivisionsY = this._subdivisionsY;
  58178. this._heightQuads = new Array();
  58179. for (var row = 0; row < subdivisionsY; row++) {
  58180. for (var col = 0; col < subdivisionsX; col++) {
  58181. 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) };
  58182. this._heightQuads[row * subdivisionsX + col] = quad;
  58183. }
  58184. }
  58185. return this;
  58186. };
  58187. // Compute each quad element values and update the the heightMap array :
  58188. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58189. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58190. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58191. // Returns the GroundMesh.
  58192. GroundMesh.prototype._computeHeightQuads = function () {
  58193. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58194. if (!positions) {
  58195. return this;
  58196. }
  58197. var v1 = BABYLON.Tmp.Vector3[3];
  58198. var v2 = BABYLON.Tmp.Vector3[2];
  58199. var v3 = BABYLON.Tmp.Vector3[1];
  58200. var v4 = BABYLON.Tmp.Vector3[0];
  58201. var v1v2 = BABYLON.Tmp.Vector3[4];
  58202. var v1v3 = BABYLON.Tmp.Vector3[5];
  58203. var v1v4 = BABYLON.Tmp.Vector3[6];
  58204. var norm1 = BABYLON.Tmp.Vector3[7];
  58205. var norm2 = BABYLON.Tmp.Vector3[8];
  58206. var i = 0;
  58207. var j = 0;
  58208. var k = 0;
  58209. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58210. var h = 0;
  58211. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58212. var d2 = 0;
  58213. var subdivisionsX = this._subdivisionsX;
  58214. var subdivisionsY = this._subdivisionsY;
  58215. for (var row = 0; row < subdivisionsY; row++) {
  58216. for (var col = 0; col < subdivisionsX; col++) {
  58217. i = col * 3;
  58218. j = row * (subdivisionsX + 1) * 3;
  58219. k = (row + 1) * (subdivisionsX + 1) * 3;
  58220. v1.x = positions[j + i];
  58221. v1.y = positions[j + i + 1];
  58222. v1.z = positions[j + i + 2];
  58223. v2.x = positions[j + i + 3];
  58224. v2.y = positions[j + i + 4];
  58225. v2.z = positions[j + i + 5];
  58226. v3.x = positions[k + i];
  58227. v3.y = positions[k + i + 1];
  58228. v3.z = positions[k + i + 2];
  58229. v4.x = positions[k + i + 3];
  58230. v4.y = positions[k + i + 4];
  58231. v4.z = positions[k + i + 5];
  58232. // 2D slope V1V4
  58233. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58234. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58235. // facet equations :
  58236. // we compute each facet normal vector
  58237. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58238. // we compute the value d by applying the equation to v1 which belongs to the plane
  58239. // then we store the facet equation in a Vector4
  58240. v2.subtractToRef(v1, v1v2);
  58241. v3.subtractToRef(v1, v1v3);
  58242. v4.subtractToRef(v1, v1v4);
  58243. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58244. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58245. norm1.normalize();
  58246. norm2.normalize();
  58247. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58248. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58249. var quad = this._heightQuads[row * subdivisionsX + col];
  58250. quad.slope.copyFromFloats(cd, h);
  58251. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58252. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58253. }
  58254. }
  58255. return this;
  58256. };
  58257. GroundMesh.prototype.serialize = function (serializationObject) {
  58258. _super.prototype.serialize.call(this, serializationObject);
  58259. serializationObject.subdivisionsX = this._subdivisionsX;
  58260. serializationObject.subdivisionsY = this._subdivisionsY;
  58261. serializationObject.minX = this._minX;
  58262. serializationObject.maxX = this._maxX;
  58263. serializationObject.minZ = this._minZ;
  58264. serializationObject.maxZ = this._maxZ;
  58265. serializationObject.width = this._width;
  58266. serializationObject.height = this._height;
  58267. };
  58268. GroundMesh.Parse = function (parsedMesh, scene) {
  58269. var result = new GroundMesh(parsedMesh.name, scene);
  58270. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58271. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58272. result._minX = parsedMesh.minX;
  58273. result._maxX = parsedMesh.maxX;
  58274. result._minZ = parsedMesh.minZ;
  58275. result._maxZ = parsedMesh.maxZ;
  58276. result._width = parsedMesh.width;
  58277. result._height = parsedMesh.height;
  58278. return result;
  58279. };
  58280. return GroundMesh;
  58281. }(BABYLON.Mesh));
  58282. BABYLON.GroundMesh = GroundMesh;
  58283. })(BABYLON || (BABYLON = {}));
  58284. //# sourceMappingURL=babylon.groundMesh.js.map
  58285. "use strict";
  58286. var BABYLON;
  58287. (function (BABYLON) {
  58288. /**
  58289. * Creates an instance based on a source mesh.
  58290. */
  58291. var InstancedMesh = /** @class */ (function (_super) {
  58292. __extends(InstancedMesh, _super);
  58293. function InstancedMesh(name, source) {
  58294. var _this = _super.call(this, name, source.getScene()) || this;
  58295. source.instances.push(_this);
  58296. _this._sourceMesh = source;
  58297. _this.position.copyFrom(source.position);
  58298. _this.rotation.copyFrom(source.rotation);
  58299. _this.scaling.copyFrom(source.scaling);
  58300. if (source.rotationQuaternion) {
  58301. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58302. }
  58303. _this.infiniteDistance = source.infiniteDistance;
  58304. _this.setPivotMatrix(source.getPivotMatrix());
  58305. _this.refreshBoundingInfo();
  58306. _this._syncSubMeshes();
  58307. return _this;
  58308. }
  58309. /**
  58310. * Returns the string "InstancedMesh".
  58311. */
  58312. InstancedMesh.prototype.getClassName = function () {
  58313. return "InstancedMesh";
  58314. };
  58315. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58316. // Methods
  58317. get: function () {
  58318. return this._sourceMesh.receiveShadows;
  58319. },
  58320. enumerable: true,
  58321. configurable: true
  58322. });
  58323. Object.defineProperty(InstancedMesh.prototype, "material", {
  58324. get: function () {
  58325. return this._sourceMesh.material;
  58326. },
  58327. enumerable: true,
  58328. configurable: true
  58329. });
  58330. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58331. get: function () {
  58332. return this._sourceMesh.visibility;
  58333. },
  58334. enumerable: true,
  58335. configurable: true
  58336. });
  58337. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58338. get: function () {
  58339. return this._sourceMesh.skeleton;
  58340. },
  58341. enumerable: true,
  58342. configurable: true
  58343. });
  58344. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58345. get: function () {
  58346. return this._sourceMesh.renderingGroupId;
  58347. },
  58348. set: function (value) {
  58349. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58350. return;
  58351. }
  58352. //no-op with warning
  58353. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58354. },
  58355. enumerable: true,
  58356. configurable: true
  58357. });
  58358. /**
  58359. * Returns the total number of vertices (integer).
  58360. */
  58361. InstancedMesh.prototype.getTotalVertices = function () {
  58362. return this._sourceMesh.getTotalVertices();
  58363. };
  58364. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58365. get: function () {
  58366. return this._sourceMesh;
  58367. },
  58368. enumerable: true,
  58369. configurable: true
  58370. });
  58371. /**
  58372. * Is this node ready to be used/rendered
  58373. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58374. * @return {boolean} is it ready
  58375. */
  58376. InstancedMesh.prototype.isReady = function (completeCheck) {
  58377. if (completeCheck === void 0) { completeCheck = false; }
  58378. return this._sourceMesh.isReady(completeCheck, true);
  58379. };
  58380. /**
  58381. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58382. */
  58383. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58384. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58385. };
  58386. /**
  58387. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58388. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58389. * The `data` are either a numeric array either a Float32Array.
  58390. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58391. * 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).
  58392. * Note that a new underlying VertexBuffer object is created each call.
  58393. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58394. *
  58395. * Possible `kind` values :
  58396. * - BABYLON.VertexBuffer.PositionKind
  58397. * - BABYLON.VertexBuffer.UVKind
  58398. * - BABYLON.VertexBuffer.UV2Kind
  58399. * - BABYLON.VertexBuffer.UV3Kind
  58400. * - BABYLON.VertexBuffer.UV4Kind
  58401. * - BABYLON.VertexBuffer.UV5Kind
  58402. * - BABYLON.VertexBuffer.UV6Kind
  58403. * - BABYLON.VertexBuffer.ColorKind
  58404. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58405. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58406. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58407. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58408. *
  58409. * Returns the Mesh.
  58410. */
  58411. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58412. if (this.sourceMesh) {
  58413. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58414. }
  58415. return this.sourceMesh;
  58416. };
  58417. /**
  58418. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58419. * If the mesh has no geometry, it is simply returned as it is.
  58420. * The `data` are either a numeric array either a Float32Array.
  58421. * No new underlying VertexBuffer object is created.
  58422. * 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.
  58423. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58424. *
  58425. * Possible `kind` values :
  58426. * - BABYLON.VertexBuffer.PositionKind
  58427. * - BABYLON.VertexBuffer.UVKind
  58428. * - BABYLON.VertexBuffer.UV2Kind
  58429. * - BABYLON.VertexBuffer.UV3Kind
  58430. * - BABYLON.VertexBuffer.UV4Kind
  58431. * - BABYLON.VertexBuffer.UV5Kind
  58432. * - BABYLON.VertexBuffer.UV6Kind
  58433. * - BABYLON.VertexBuffer.ColorKind
  58434. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58435. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58436. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58437. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58438. *
  58439. * Returns the Mesh.
  58440. */
  58441. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58442. if (this.sourceMesh) {
  58443. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58444. }
  58445. return this.sourceMesh;
  58446. };
  58447. /**
  58448. * Sets the mesh indices.
  58449. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58450. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58451. * This method creates a new index buffer each call.
  58452. * Returns the Mesh.
  58453. */
  58454. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58455. if (totalVertices === void 0) { totalVertices = null; }
  58456. if (this.sourceMesh) {
  58457. this.sourceMesh.setIndices(indices, totalVertices);
  58458. }
  58459. return this.sourceMesh;
  58460. };
  58461. /**
  58462. * Boolean : True if the mesh owns the requested kind of data.
  58463. */
  58464. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58465. return this._sourceMesh.isVerticesDataPresent(kind);
  58466. };
  58467. /**
  58468. * Returns an array of indices (IndicesArray).
  58469. */
  58470. InstancedMesh.prototype.getIndices = function () {
  58471. return this._sourceMesh.getIndices();
  58472. };
  58473. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58474. get: function () {
  58475. return this._sourceMesh._positions;
  58476. },
  58477. enumerable: true,
  58478. configurable: true
  58479. });
  58480. /**
  58481. * Sets a new updated BoundingInfo to the mesh.
  58482. * Returns the mesh.
  58483. */
  58484. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58485. var meshBB = this._sourceMesh.getBoundingInfo();
  58486. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58487. this._updateBoundingInfo();
  58488. return this;
  58489. };
  58490. InstancedMesh.prototype._preActivate = function () {
  58491. if (this._currentLOD) {
  58492. this._currentLOD._preActivate();
  58493. }
  58494. return this;
  58495. };
  58496. InstancedMesh.prototype._activate = function (renderId) {
  58497. if (this._currentLOD) {
  58498. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58499. }
  58500. return this;
  58501. };
  58502. /**
  58503. * Returns the current associated LOD AbstractMesh.
  58504. */
  58505. InstancedMesh.prototype.getLOD = function (camera) {
  58506. if (!camera) {
  58507. return this;
  58508. }
  58509. var boundingInfo = this.getBoundingInfo();
  58510. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58511. if (this._currentLOD === this.sourceMesh) {
  58512. return this;
  58513. }
  58514. return this._currentLOD;
  58515. };
  58516. InstancedMesh.prototype._syncSubMeshes = function () {
  58517. this.releaseSubMeshes();
  58518. if (this._sourceMesh.subMeshes) {
  58519. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58520. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58521. }
  58522. }
  58523. return this;
  58524. };
  58525. InstancedMesh.prototype._generatePointsArray = function () {
  58526. return this._sourceMesh._generatePointsArray();
  58527. };
  58528. /**
  58529. * Creates a new InstancedMesh from the current mesh.
  58530. * - name (string) : the cloned mesh name
  58531. * - newParent (optional Node) : the optional Node to parent the clone to.
  58532. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58533. *
  58534. * Returns the clone.
  58535. */
  58536. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58537. var result = this._sourceMesh.createInstance(name);
  58538. // Deep copy
  58539. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58540. // Bounding info
  58541. this.refreshBoundingInfo();
  58542. // Parent
  58543. if (newParent) {
  58544. result.parent = newParent;
  58545. }
  58546. if (!doNotCloneChildren) {
  58547. // Children
  58548. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58549. var mesh = this.getScene().meshes[index];
  58550. if (mesh.parent === this) {
  58551. mesh.clone(mesh.name, result);
  58552. }
  58553. }
  58554. }
  58555. result.computeWorldMatrix(true);
  58556. return result;
  58557. };
  58558. /**
  58559. * Disposes the InstancedMesh.
  58560. * Returns nothing.
  58561. */
  58562. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58563. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58564. // Remove from mesh
  58565. var index = this._sourceMesh.instances.indexOf(this);
  58566. this._sourceMesh.instances.splice(index, 1);
  58567. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58568. };
  58569. return InstancedMesh;
  58570. }(BABYLON.AbstractMesh));
  58571. BABYLON.InstancedMesh = InstancedMesh;
  58572. })(BABYLON || (BABYLON = {}));
  58573. //# sourceMappingURL=babylon.instancedMesh.js.map
  58574. "use strict";
  58575. var BABYLON;
  58576. (function (BABYLON) {
  58577. var LinesMesh = /** @class */ (function (_super) {
  58578. __extends(LinesMesh, _super);
  58579. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58580. if (scene === void 0) { scene = null; }
  58581. if (parent === void 0) { parent = null; }
  58582. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58583. _this.useVertexColor = useVertexColor;
  58584. _this.useVertexAlpha = useVertexAlpha;
  58585. _this.color = new BABYLON.Color3(1, 1, 1);
  58586. _this.alpha = 1;
  58587. if (source) {
  58588. _this.color = source.color.clone();
  58589. _this.alpha = source.alpha;
  58590. _this.useVertexColor = source.useVertexColor;
  58591. _this.useVertexAlpha = source.useVertexAlpha;
  58592. }
  58593. _this._intersectionThreshold = 0.1;
  58594. var defines = [];
  58595. var options = {
  58596. attributes: [BABYLON.VertexBuffer.PositionKind],
  58597. uniforms: ["world", "viewProjection"],
  58598. needAlphaBlending: true,
  58599. defines: defines
  58600. };
  58601. if (useVertexAlpha === false) {
  58602. options.needAlphaBlending = false;
  58603. }
  58604. if (!useVertexColor) {
  58605. options.uniforms.push("color");
  58606. }
  58607. else {
  58608. options.defines.push("#define VERTEXCOLOR");
  58609. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58610. }
  58611. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58612. return _this;
  58613. }
  58614. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58615. /**
  58616. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58617. * This margin is expressed in world space coordinates, so its value may vary.
  58618. * Default value is 0.1
  58619. * @returns the intersection Threshold value.
  58620. */
  58621. get: function () {
  58622. return this._intersectionThreshold;
  58623. },
  58624. /**
  58625. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58626. * This margin is expressed in world space coordinates, so its value may vary.
  58627. * @param value the new threshold to apply
  58628. */
  58629. set: function (value) {
  58630. if (this._intersectionThreshold === value) {
  58631. return;
  58632. }
  58633. this._intersectionThreshold = value;
  58634. if (this.geometry) {
  58635. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58636. }
  58637. },
  58638. enumerable: true,
  58639. configurable: true
  58640. });
  58641. /**
  58642. * Returns the string "LineMesh"
  58643. */
  58644. LinesMesh.prototype.getClassName = function () {
  58645. return "LinesMesh";
  58646. };
  58647. Object.defineProperty(LinesMesh.prototype, "material", {
  58648. get: function () {
  58649. return this._colorShader;
  58650. },
  58651. set: function (value) {
  58652. // Do nothing
  58653. },
  58654. enumerable: true,
  58655. configurable: true
  58656. });
  58657. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58658. get: function () {
  58659. return false;
  58660. },
  58661. enumerable: true,
  58662. configurable: true
  58663. });
  58664. LinesMesh.prototype.createInstance = function (name) {
  58665. throw new Error("LinesMeshes do not support createInstance.");
  58666. };
  58667. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58668. if (!this._geometry) {
  58669. return this;
  58670. }
  58671. // VBOs
  58672. this._geometry._bind(this._colorShader.getEffect());
  58673. // Color
  58674. if (!this.useVertexColor) {
  58675. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58676. }
  58677. return this;
  58678. };
  58679. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58680. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58681. return this;
  58682. }
  58683. var engine = this.getScene().getEngine();
  58684. // Draw order
  58685. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58686. return this;
  58687. };
  58688. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58689. this._colorShader.dispose();
  58690. _super.prototype.dispose.call(this, doNotRecurse);
  58691. };
  58692. /**
  58693. * Returns a new LineMesh object cloned from the current one.
  58694. */
  58695. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58696. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58697. };
  58698. return LinesMesh;
  58699. }(BABYLON.Mesh));
  58700. BABYLON.LinesMesh = LinesMesh;
  58701. })(BABYLON || (BABYLON = {}));
  58702. //# sourceMappingURL=babylon.linesMesh.js.map
  58703. "use strict";
  58704. var BABYLON;
  58705. (function (BABYLON) {
  58706. var MeshBuilder = /** @class */ (function () {
  58707. function MeshBuilder() {
  58708. }
  58709. MeshBuilder.updateSideOrientation = function (orientation) {
  58710. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  58711. return BABYLON.Mesh.DOUBLESIDE;
  58712. }
  58713. if (orientation === undefined || orientation === null) {
  58714. return BABYLON.Mesh.FRONTSIDE;
  58715. }
  58716. return orientation;
  58717. };
  58718. /**
  58719. * Creates a box mesh.
  58720. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  58721. * The parameter `size` sets the size (float) of each box side (default 1).
  58722. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  58723. * 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).
  58724. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  58725. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58726. * 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).
  58727. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58729. */
  58730. MeshBuilder.CreateBox = function (name, options, scene) {
  58731. if (scene === void 0) { scene = null; }
  58732. var box = new BABYLON.Mesh(name, scene);
  58733. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58734. box._originalBuilderSideOrientation = options.sideOrientation;
  58735. var vertexData = BABYLON.VertexData.CreateBox(options);
  58736. vertexData.applyToMesh(box, options.updatable);
  58737. return box;
  58738. };
  58739. /**
  58740. * Creates a sphere mesh.
  58741. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  58742. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  58743. * 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`).
  58744. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  58745. * 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
  58746. * 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).
  58747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58748. * 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).
  58749. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58751. */
  58752. MeshBuilder.CreateSphere = function (name, options, scene) {
  58753. var sphere = new BABYLON.Mesh(name, scene);
  58754. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58755. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58756. var vertexData = BABYLON.VertexData.CreateSphere(options);
  58757. vertexData.applyToMesh(sphere, options.updatable);
  58758. return sphere;
  58759. };
  58760. /**
  58761. * Creates a plane polygonal mesh. By default, this is a disc.
  58762. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  58763. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  58764. * 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.
  58765. * 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
  58766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58767. * 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).
  58768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58770. */
  58771. MeshBuilder.CreateDisc = function (name, options, scene) {
  58772. if (scene === void 0) { scene = null; }
  58773. var disc = new BABYLON.Mesh(name, scene);
  58774. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58775. disc._originalBuilderSideOrientation = options.sideOrientation;
  58776. var vertexData = BABYLON.VertexData.CreateDisc(options);
  58777. vertexData.applyToMesh(disc, options.updatable);
  58778. return disc;
  58779. };
  58780. /**
  58781. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  58782. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  58783. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  58784. * 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`).
  58785. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  58786. * 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.
  58787. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58788. * 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).
  58789. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58791. */
  58792. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  58793. var sphere = new BABYLON.Mesh(name, scene);
  58794. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58795. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58796. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  58797. vertexData.applyToMesh(sphere, options.updatable);
  58798. return sphere;
  58799. };
  58800. ;
  58801. /**
  58802. * Creates a ribbon mesh.
  58803. * 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.
  58804. *
  58805. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  58806. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  58807. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  58808. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  58809. * 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.
  58810. * 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.
  58811. * 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
  58812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58813. * 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).
  58814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58815. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  58816. * 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.
  58817. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  58818. * 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
  58819. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  58820. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  58821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58822. */
  58823. MeshBuilder.CreateRibbon = function (name, options, scene) {
  58824. if (scene === void 0) { scene = null; }
  58825. var pathArray = options.pathArray;
  58826. var closeArray = options.closeArray;
  58827. var closePath = options.closePath;
  58828. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58829. var instance = options.instance;
  58830. var updatable = options.updatable;
  58831. if (instance) {
  58832. // positionFunction : ribbon case
  58833. // only pathArray and sideOrientation parameters are taken into account for positions update
  58834. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  58835. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  58836. var positionFunction = function (positions) {
  58837. var minlg = pathArray[0].length;
  58838. var i = 0;
  58839. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  58840. for (var si = 1; si <= ns; si++) {
  58841. for (var p = 0; p < pathArray.length; p++) {
  58842. var path = pathArray[p];
  58843. var l = path.length;
  58844. minlg = (minlg < l) ? minlg : l;
  58845. var j = 0;
  58846. while (j < minlg) {
  58847. positions[i] = path[j].x;
  58848. positions[i + 1] = path[j].y;
  58849. positions[i + 2] = path[j].z;
  58850. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  58851. BABYLON.Tmp.Vector3[0].x = path[j].x;
  58852. }
  58853. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  58854. BABYLON.Tmp.Vector3[1].x = path[j].x;
  58855. }
  58856. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  58857. BABYLON.Tmp.Vector3[0].y = path[j].y;
  58858. }
  58859. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  58860. BABYLON.Tmp.Vector3[1].y = path[j].y;
  58861. }
  58862. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  58863. BABYLON.Tmp.Vector3[0].z = path[j].z;
  58864. }
  58865. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  58866. BABYLON.Tmp.Vector3[1].z = path[j].z;
  58867. }
  58868. j++;
  58869. i += 3;
  58870. }
  58871. if (instance._closePath) {
  58872. positions[i] = path[0].x;
  58873. positions[i + 1] = path[0].y;
  58874. positions[i + 2] = path[0].z;
  58875. i += 3;
  58876. }
  58877. }
  58878. }
  58879. };
  58880. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58881. positionFunction(positions);
  58882. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  58883. instance._boundingInfo.update(instance._worldMatrix);
  58884. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  58885. if (options.colors) {
  58886. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58887. for (var c = 0; c < options.colors.length; c++) {
  58888. colors[c * 4] = options.colors[c].r;
  58889. colors[c * 4 + 1] = options.colors[c].g;
  58890. colors[c * 4 + 2] = options.colors[c].b;
  58891. colors[c * 4 + 3] = options.colors[c].a;
  58892. }
  58893. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  58894. }
  58895. if (options.uvs) {
  58896. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58897. for (var i = 0; i < options.uvs.length; i++) {
  58898. uvs[i * 2] = options.uvs[i].x;
  58899. uvs[i * 2 + 1] = options.uvs[i].y;
  58900. }
  58901. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  58902. }
  58903. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  58904. var indices = instance.getIndices();
  58905. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58906. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  58907. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  58908. if (instance._closePath) {
  58909. var indexFirst = 0;
  58910. var indexLast = 0;
  58911. for (var p = 0; p < pathArray.length; p++) {
  58912. indexFirst = instance._idx[p] * 3;
  58913. if (p + 1 < pathArray.length) {
  58914. indexLast = (instance._idx[p + 1] - 1) * 3;
  58915. }
  58916. else {
  58917. indexLast = normals.length - 3;
  58918. }
  58919. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  58920. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  58921. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  58922. normals[indexLast] = normals[indexFirst];
  58923. normals[indexLast + 1] = normals[indexFirst + 1];
  58924. normals[indexLast + 2] = normals[indexFirst + 2];
  58925. }
  58926. }
  58927. if (!(instance.areNormalsFrozen)) {
  58928. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  58929. }
  58930. }
  58931. return instance;
  58932. }
  58933. else {
  58934. var ribbon = new BABYLON.Mesh(name, scene);
  58935. ribbon._originalBuilderSideOrientation = sideOrientation;
  58936. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  58937. if (closePath) {
  58938. ribbon._idx = vertexData._idx;
  58939. }
  58940. ribbon._closePath = closePath;
  58941. ribbon._closeArray = closeArray;
  58942. vertexData.applyToMesh(ribbon, updatable);
  58943. return ribbon;
  58944. }
  58945. };
  58946. /**
  58947. * Creates a cylinder or a cone mesh.
  58948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  58949. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  58950. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  58951. * 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.
  58952. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  58953. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  58954. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  58955. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  58956. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  58957. * 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).
  58958. * 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
  58959. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  58960. * 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
  58961. * 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.
  58962. * If `enclose` is false, a ring surface is one element.
  58963. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  58964. * 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
  58965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58966. * 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).
  58967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58969. */
  58970. MeshBuilder.CreateCylinder = function (name, options, scene) {
  58971. var cylinder = new BABYLON.Mesh(name, scene);
  58972. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58973. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  58974. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  58975. vertexData.applyToMesh(cylinder, options.updatable);
  58976. return cylinder;
  58977. };
  58978. /**
  58979. * Creates a torus mesh.
  58980. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  58981. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  58982. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  58983. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  58984. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58985. * 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).
  58986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58988. */
  58989. MeshBuilder.CreateTorus = function (name, options, scene) {
  58990. var torus = new BABYLON.Mesh(name, scene);
  58991. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58992. torus._originalBuilderSideOrientation = options.sideOrientation;
  58993. var vertexData = BABYLON.VertexData.CreateTorus(options);
  58994. vertexData.applyToMesh(torus, options.updatable);
  58995. return torus;
  58996. };
  58997. /**
  58998. * Creates a torus knot mesh.
  58999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59000. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  59001. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  59002. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  59003. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  59004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59005. * 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).
  59006. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59008. */
  59009. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59010. var torusKnot = new BABYLON.Mesh(name, scene);
  59011. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59012. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59013. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59014. vertexData.applyToMesh(torusKnot, options.updatable);
  59015. return torusKnot;
  59016. };
  59017. /**
  59018. * Creates a line system mesh.
  59019. * A line system is a pool of many lines gathered in a single mesh.
  59020. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59021. * 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.
  59022. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  59023. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  59024. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  59025. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  59026. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  59027. * 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
  59028. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  59029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59030. */
  59031. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59032. var instance = options.instance;
  59033. var lines = options.lines;
  59034. var colors = options.colors;
  59035. if (instance) {
  59036. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59037. var vertexColor;
  59038. var lineColors;
  59039. if (colors) {
  59040. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59041. }
  59042. var i = 0;
  59043. var c = 0;
  59044. for (var l = 0; l < lines.length; l++) {
  59045. var points = lines[l];
  59046. for (var p = 0; p < points.length; p++) {
  59047. positions[i] = points[p].x;
  59048. positions[i + 1] = points[p].y;
  59049. positions[i + 2] = points[p].z;
  59050. if (colors && vertexColor) {
  59051. lineColors = colors[l];
  59052. vertexColor[c] = lineColors[p].r;
  59053. vertexColor[c + 1] = lineColors[p].g;
  59054. vertexColor[c + 2] = lineColors[p].b;
  59055. vertexColor[c + 3] = lineColors[p].a;
  59056. c += 4;
  59057. }
  59058. i += 3;
  59059. }
  59060. }
  59061. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59062. if (colors && vertexColor) {
  59063. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59064. }
  59065. return instance;
  59066. }
  59067. // line system creation
  59068. var useVertexColor = (colors) ? true : false;
  59069. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59070. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59071. vertexData.applyToMesh(lineSystem, options.updatable);
  59072. return lineSystem;
  59073. };
  59074. /**
  59075. * Creates a line mesh.
  59076. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59077. * 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.
  59078. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  59079. * The parameter `points` is an array successive Vector3.
  59080. * 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
  59081. * The optional parameter `colors` is an array of successive Color4, one per line point.
  59082. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  59083. * When updating an instance, remember that only point positions can change, not the number of points.
  59084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59085. */
  59086. MeshBuilder.CreateLines = function (name, options, scene) {
  59087. if (scene === void 0) { scene = null; }
  59088. var colors = (options.colors) ? [options.colors] : null;
  59089. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59090. return lines;
  59091. };
  59092. /**
  59093. * Creates a dashed line mesh.
  59094. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59095. * 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.
  59096. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  59097. * The parameter `points` is an array successive Vector3.
  59098. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  59099. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  59100. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  59101. * 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
  59102. * When updating an instance, remember that only point positions can change, not the number of points.
  59103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59104. */
  59105. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59106. if (scene === void 0) { scene = null; }
  59107. var points = options.points;
  59108. var instance = options.instance;
  59109. var gapSize = options.gapSize || 1;
  59110. var dashSize = options.dashSize || 3;
  59111. if (instance) {
  59112. var positionFunction = function (positions) {
  59113. var curvect = BABYLON.Vector3.Zero();
  59114. var nbSeg = positions.length / 6;
  59115. var lg = 0;
  59116. var nb = 0;
  59117. var shft = 0;
  59118. var dashshft = 0;
  59119. var curshft = 0;
  59120. var p = 0;
  59121. var i = 0;
  59122. var j = 0;
  59123. for (i = 0; i < points.length - 1; i++) {
  59124. points[i + 1].subtractToRef(points[i], curvect);
  59125. lg += curvect.length();
  59126. }
  59127. shft = lg / nbSeg;
  59128. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59129. for (i = 0; i < points.length - 1; i++) {
  59130. points[i + 1].subtractToRef(points[i], curvect);
  59131. nb = Math.floor(curvect.length() / shft);
  59132. curvect.normalize();
  59133. j = 0;
  59134. while (j < nb && p < positions.length) {
  59135. curshft = shft * j;
  59136. positions[p] = points[i].x + curshft * curvect.x;
  59137. positions[p + 1] = points[i].y + curshft * curvect.y;
  59138. positions[p + 2] = points[i].z + curshft * curvect.z;
  59139. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59140. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59141. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59142. p += 6;
  59143. j++;
  59144. }
  59145. }
  59146. while (p < positions.length) {
  59147. positions[p] = points[i].x;
  59148. positions[p + 1] = points[i].y;
  59149. positions[p + 2] = points[i].z;
  59150. p += 3;
  59151. }
  59152. };
  59153. instance.updateMeshPositions(positionFunction, false);
  59154. return instance;
  59155. }
  59156. // dashed lines creation
  59157. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59158. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59159. vertexData.applyToMesh(dashedLines, options.updatable);
  59160. dashedLines.dashSize = dashSize;
  59161. dashedLines.gapSize = gapSize;
  59162. return dashedLines;
  59163. };
  59164. /**
  59165. * Creates an extruded shape mesh.
  59166. * 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.
  59167. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59168. *
  59169. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59170. * 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
  59171. * extruded along the Z axis.
  59172. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59173. * 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.
  59174. * The parameter `scale` (float, default 1) is the value to scale the shape.
  59175. * 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
  59176. * 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
  59177. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59179. * 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).
  59180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59181. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59183. */
  59184. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59185. if (scene === void 0) { scene = null; }
  59186. var path = options.path;
  59187. var shape = options.shape;
  59188. var scale = options.scale || 1;
  59189. var rotation = options.rotation || 0;
  59190. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59191. var updatable = options.updatable;
  59192. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59193. var instance = options.instance || null;
  59194. var invertUV = options.invertUV || false;
  59195. 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);
  59196. };
  59197. /**
  59198. * Creates an custom extruded shape mesh.
  59199. * 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.
  59200. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59201. *
  59202. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59203. * 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
  59204. * extruded along the Z axis.
  59205. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59206. * 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
  59207. * and the distance of this point from the begining of the path :
  59208. * ```javascript
  59209. * var rotationFunction = function(i, distance) {
  59210. * // do things
  59211. * return rotationValue; }
  59212. * ```
  59213. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59214. * 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
  59215. * and the distance of this point from the begining of the path :
  59216. * ```javascript
  59217. * var scaleFunction = function(i, distance) {
  59218. * // do things
  59219. * return scaleValue;}
  59220. * ```
  59221. * It must returns a float value that will be the scale value applied to the shape on each path point.
  59222. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  59223. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  59224. * 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
  59225. * 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
  59226. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59227. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59228. * 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).
  59229. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59230. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59232. */
  59233. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59234. var path = options.path;
  59235. var shape = options.shape;
  59236. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59237. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59238. var ribbonCloseArray = options.ribbonCloseArray || false;
  59239. var ribbonClosePath = options.ribbonClosePath || false;
  59240. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59241. var updatable = options.updatable;
  59242. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59243. var instance = options.instance;
  59244. var invertUV = options.invertUV || false;
  59245. 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);
  59246. };
  59247. /**
  59248. * Creates lathe mesh.
  59249. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  59250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59251. *
  59252. * 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
  59253. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  59254. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  59255. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  59256. * 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.
  59257. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  59258. * 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
  59259. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59260. * 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).
  59261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59262. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59264. */
  59265. MeshBuilder.CreateLathe = function (name, options, scene) {
  59266. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59267. var closed = (options.closed === undefined) ? true : options.closed;
  59268. var shape = options.shape;
  59269. var radius = options.radius || 1;
  59270. var tessellation = options.tessellation || 64;
  59271. var updatable = options.updatable;
  59272. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59273. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59274. var pi2 = Math.PI * 2;
  59275. var paths = new Array();
  59276. var invertUV = options.invertUV || false;
  59277. var i = 0;
  59278. var p = 0;
  59279. var step = pi2 / tessellation * arc;
  59280. var rotated;
  59281. var path = new Array();
  59282. ;
  59283. for (i = 0; i <= tessellation; i++) {
  59284. var path = [];
  59285. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59286. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59287. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59288. }
  59289. for (p = 0; p < shape.length; p++) {
  59290. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59291. path.push(rotated);
  59292. }
  59293. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59294. 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));
  59295. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59296. }
  59297. paths.push(path);
  59298. }
  59299. // lathe ribbon
  59300. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59301. return lathe;
  59302. };
  59303. /**
  59304. * Creates a plane mesh.
  59305. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59306. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  59307. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  59308. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  59309. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59310. * 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).
  59311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59313. */
  59314. MeshBuilder.CreatePlane = function (name, options, scene) {
  59315. var plane = new BABYLON.Mesh(name, scene);
  59316. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59317. plane._originalBuilderSideOrientation = options.sideOrientation;
  59318. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59319. vertexData.applyToMesh(plane, options.updatable);
  59320. if (options.sourcePlane) {
  59321. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59322. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59323. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59324. plane.rotate(vectorProduct, product);
  59325. }
  59326. return plane;
  59327. };
  59328. /**
  59329. * Creates a ground mesh.
  59330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59331. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  59332. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  59333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59334. */
  59335. MeshBuilder.CreateGround = function (name, options, scene) {
  59336. var ground = new BABYLON.GroundMesh(name, scene);
  59337. ground._setReady(false);
  59338. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59339. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59340. ground._width = options.width || 1;
  59341. ground._height = options.height || 1;
  59342. ground._maxX = ground._width / 2;
  59343. ground._maxZ = ground._height / 2;
  59344. ground._minX = -ground._maxX;
  59345. ground._minZ = -ground._maxZ;
  59346. var vertexData = BABYLON.VertexData.CreateGround(options);
  59347. vertexData.applyToMesh(ground, options.updatable);
  59348. ground._setReady(true);
  59349. return ground;
  59350. };
  59351. /**
  59352. * Creates a tiled ground mesh.
  59353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  59354. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  59355. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  59356. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  59357. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  59358. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  59359. * numbers of subdivisions on the ground width and height of each tile.
  59360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59361. */
  59362. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  59363. var tiledGround = new BABYLON.Mesh(name, scene);
  59364. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  59365. vertexData.applyToMesh(tiledGround, options.updatable);
  59366. return tiledGround;
  59367. };
  59368. /**
  59369. * Creates a ground mesh from a height map.
  59370. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  59371. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  59372. * The parameter `url` sets the URL of the height map image resource.
  59373. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  59374. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  59375. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  59376. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  59377. * 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.
  59378. * 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).
  59379. * This function is passed the newly built mesh :
  59380. * ```javascript
  59381. * function(mesh) { // do things
  59382. * return; }
  59383. * ```
  59384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59385. */
  59386. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  59387. var width = options.width || 10.0;
  59388. var height = options.height || 10.0;
  59389. var subdivisions = options.subdivisions || 1 | 0;
  59390. var minHeight = options.minHeight || 0.0;
  59391. var maxHeight = options.maxHeight || 1.0;
  59392. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  59393. var updatable = options.updatable;
  59394. var onReady = options.onReady;
  59395. var ground = new BABYLON.GroundMesh(name, scene);
  59396. ground._subdivisionsX = subdivisions;
  59397. ground._subdivisionsY = subdivisions;
  59398. ground._width = width;
  59399. ground._height = height;
  59400. ground._maxX = ground._width / 2.0;
  59401. ground._maxZ = ground._height / 2.0;
  59402. ground._minX = -ground._maxX;
  59403. ground._minZ = -ground._maxZ;
  59404. ground._setReady(false);
  59405. var onload = function (img) {
  59406. // Getting height map data
  59407. var canvas = document.createElement("canvas");
  59408. var context = canvas.getContext("2d");
  59409. if (!context) {
  59410. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  59411. }
  59412. if (scene.isDisposed) {
  59413. return;
  59414. }
  59415. var bufferWidth = img.width;
  59416. var bufferHeight = img.height;
  59417. canvas.width = bufferWidth;
  59418. canvas.height = bufferHeight;
  59419. context.drawImage(img, 0, 0);
  59420. // Create VertexData from map data
  59421. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  59422. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  59423. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  59424. width: width, height: height,
  59425. subdivisions: subdivisions,
  59426. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  59427. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  59428. });
  59429. vertexData.applyToMesh(ground, updatable);
  59430. //execute ready callback, if set
  59431. if (onReady) {
  59432. onReady(ground);
  59433. }
  59434. ground._setReady(true);
  59435. };
  59436. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  59437. return ground;
  59438. };
  59439. /**
  59440. * Creates a polygon mesh.
  59441. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  59442. * 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.
  59443. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59445. * 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).
  59446. * Remember you can only change the shape positions, not their number when updating a polygon.
  59447. */
  59448. MeshBuilder.CreatePolygon = function (name, options, scene) {
  59449. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59450. var shape = options.shape;
  59451. var holes = options.holes || [];
  59452. var depth = options.depth || 0;
  59453. var contours = [];
  59454. var hole = [];
  59455. for (var i = 0; i < shape.length; i++) {
  59456. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  59457. }
  59458. var epsilon = 0.00000001;
  59459. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  59460. contours.pop();
  59461. }
  59462. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  59463. for (var hNb = 0; hNb < holes.length; hNb++) {
  59464. hole = [];
  59465. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  59466. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  59467. }
  59468. polygonTriangulation.addHole(hole);
  59469. }
  59470. var polygon = polygonTriangulation.build(options.updatable, depth);
  59471. polygon._originalBuilderSideOrientation = options.sideOrientation;
  59472. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  59473. vertexData.applyToMesh(polygon, options.updatable);
  59474. return polygon;
  59475. };
  59476. ;
  59477. /**
  59478. * Creates an extruded polygon mesh, with depth in the Y direction.
  59479. * 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).
  59480. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59481. */
  59482. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  59483. return MeshBuilder.CreatePolygon(name, options, scene);
  59484. };
  59485. ;
  59486. /**
  59487. * Creates a tube mesh.
  59488. * 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.
  59489. *
  59490. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  59491. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  59492. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  59493. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  59494. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  59495. * 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.
  59496. * It must return a radius value (positive float) :
  59497. * ```javascript
  59498. * var radiusFunction = function(i, distance) {
  59499. * // do things
  59500. * return radius; }
  59501. * ```
  59502. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  59503. * 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
  59504. * 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
  59505. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59506. * 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).
  59507. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59508. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59510. */
  59511. MeshBuilder.CreateTube = function (name, options, scene) {
  59512. var path = options.path;
  59513. var instance = options.instance;
  59514. var radius = 1.0;
  59515. if (instance) {
  59516. radius = instance.radius;
  59517. }
  59518. if (options.radius !== undefined) {
  59519. radius = options.radius;
  59520. }
  59521. ;
  59522. var tessellation = options.tessellation || 64 | 0;
  59523. var radiusFunction = options.radiusFunction || null;
  59524. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59525. var invertUV = options.invertUV || false;
  59526. var updatable = options.updatable;
  59527. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59528. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  59529. // tube geometry
  59530. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  59531. var tangents = path3D.getTangents();
  59532. var normals = path3D.getNormals();
  59533. var distances = path3D.getDistances();
  59534. var pi2 = Math.PI * 2;
  59535. var step = pi2 / tessellation * arc;
  59536. var returnRadius = function () { return radius; };
  59537. var radiusFunctionFinal = radiusFunction || returnRadius;
  59538. var circlePath;
  59539. var rad;
  59540. var normal;
  59541. var rotated;
  59542. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59543. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59544. for (var i = 0; i < path.length; i++) {
  59545. rad = radiusFunctionFinal(i, distances[i]); // current radius
  59546. circlePath = Array(); // current circle array
  59547. normal = normals[i]; // current normal
  59548. for (var t = 0; t < tessellation; t++) {
  59549. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  59550. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  59551. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  59552. rotated.scaleInPlace(rad).addInPlace(path[i]);
  59553. circlePath[t] = rotated;
  59554. }
  59555. circlePaths[index] = circlePath;
  59556. index++;
  59557. }
  59558. // cap
  59559. var capPath = function (nbPoints, pathIndex) {
  59560. var pointCap = Array();
  59561. for (var i = 0; i < nbPoints; i++) {
  59562. pointCap.push(path[pathIndex]);
  59563. }
  59564. return pointCap;
  59565. };
  59566. switch (cap) {
  59567. case BABYLON.Mesh.NO_CAP:
  59568. break;
  59569. case BABYLON.Mesh.CAP_START:
  59570. circlePaths[0] = capPath(tessellation, 0);
  59571. circlePaths[1] = circlePaths[2].slice(0);
  59572. break;
  59573. case BABYLON.Mesh.CAP_END:
  59574. circlePaths[index] = circlePaths[index - 1].slice(0);
  59575. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59576. break;
  59577. case BABYLON.Mesh.CAP_ALL:
  59578. circlePaths[0] = capPath(tessellation, 0);
  59579. circlePaths[1] = circlePaths[2].slice(0);
  59580. circlePaths[index] = circlePaths[index - 1].slice(0);
  59581. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59582. break;
  59583. default:
  59584. break;
  59585. }
  59586. return circlePaths;
  59587. };
  59588. var path3D;
  59589. var pathArray;
  59590. if (instance) {
  59591. var arc = options.arc || instance.arc;
  59592. path3D = (instance.path3D).update(path);
  59593. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  59594. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  59595. instance.path3D = path3D;
  59596. instance.pathArray = pathArray;
  59597. instance.arc = arc;
  59598. instance.radius = radius;
  59599. return instance;
  59600. }
  59601. // tube creation
  59602. path3D = new BABYLON.Path3D(path);
  59603. var newPathArray = new Array();
  59604. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59605. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  59606. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59607. tube.pathArray = pathArray;
  59608. tube.path3D = path3D;
  59609. tube.tessellation = tessellation;
  59610. tube.cap = cap;
  59611. tube.arc = options.arc;
  59612. tube.radius = radius;
  59613. return tube;
  59614. };
  59615. /**
  59616. * Creates a polyhedron mesh.
  59617. *
  59618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  59619. * 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
  59620. * to choose the wanted type.
  59621. * The parameter `size` (positive float, default 1) sets the polygon size.
  59622. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  59623. * 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`.
  59624. * 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
  59625. * 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)`).
  59626. * 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
  59627. * 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.
  59628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59629. * 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).
  59630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59632. */
  59633. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  59634. var polyhedron = new BABYLON.Mesh(name, scene);
  59635. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59636. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  59637. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  59638. vertexData.applyToMesh(polyhedron, options.updatable);
  59639. return polyhedron;
  59640. };
  59641. /**
  59642. * Creates a decal mesh.
  59643. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  59644. * 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.
  59645. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  59646. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  59647. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  59648. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  59649. */
  59650. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  59651. var indices = sourceMesh.getIndices();
  59652. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59653. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59654. var position = options.position || BABYLON.Vector3.Zero();
  59655. var normal = options.normal || BABYLON.Vector3.Up();
  59656. var size = options.size || BABYLON.Vector3.One();
  59657. var angle = options.angle || 0;
  59658. // Getting correct rotation
  59659. if (!normal) {
  59660. var target = new BABYLON.Vector3(0, 0, 1);
  59661. var camera = sourceMesh.getScene().activeCamera;
  59662. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  59663. normal = camera.globalPosition.subtract(cameraWorldTarget);
  59664. }
  59665. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  59666. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  59667. var pitch = Math.atan2(normal.y, len);
  59668. // Matrix
  59669. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  59670. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  59671. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  59672. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  59673. var vertexData = new BABYLON.VertexData();
  59674. vertexData.indices = [];
  59675. vertexData.positions = [];
  59676. vertexData.normals = [];
  59677. vertexData.uvs = [];
  59678. var currentVertexDataIndex = 0;
  59679. var extractDecalVector3 = function (indexId) {
  59680. var result = new BABYLON.PositionNormalVertex();
  59681. if (!indices || !positions || !normals) {
  59682. return result;
  59683. }
  59684. var vertexId = indices[indexId];
  59685. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  59686. // Send vector to decal local world
  59687. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  59688. // Get normal
  59689. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  59690. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  59691. return result;
  59692. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  59693. var clip = function (vertices, axis) {
  59694. if (vertices.length === 0) {
  59695. return vertices;
  59696. }
  59697. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  59698. var clipVertices = function (v0, v1) {
  59699. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  59700. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  59701. };
  59702. var result = new Array();
  59703. for (var index = 0; index < vertices.length; index += 3) {
  59704. var v1Out;
  59705. var v2Out;
  59706. var v3Out;
  59707. var total = 0;
  59708. var nV1 = null;
  59709. var nV2 = null;
  59710. var nV3 = null;
  59711. var nV4 = null;
  59712. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  59713. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  59714. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  59715. v1Out = d1 > 0;
  59716. v2Out = d2 > 0;
  59717. v3Out = d3 > 0;
  59718. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  59719. switch (total) {
  59720. case 0:
  59721. result.push(vertices[index]);
  59722. result.push(vertices[index + 1]);
  59723. result.push(vertices[index + 2]);
  59724. break;
  59725. case 1:
  59726. if (v1Out) {
  59727. nV1 = vertices[index + 1];
  59728. nV2 = vertices[index + 2];
  59729. nV3 = clipVertices(vertices[index], nV1);
  59730. nV4 = clipVertices(vertices[index], nV2);
  59731. }
  59732. if (v2Out) {
  59733. nV1 = vertices[index];
  59734. nV2 = vertices[index + 2];
  59735. nV3 = clipVertices(vertices[index + 1], nV1);
  59736. nV4 = clipVertices(vertices[index + 1], nV2);
  59737. result.push(nV3);
  59738. result.push(nV2.clone());
  59739. result.push(nV1.clone());
  59740. result.push(nV2.clone());
  59741. result.push(nV3.clone());
  59742. result.push(nV4);
  59743. break;
  59744. }
  59745. if (v3Out) {
  59746. nV1 = vertices[index];
  59747. nV2 = vertices[index + 1];
  59748. nV3 = clipVertices(vertices[index + 2], nV1);
  59749. nV4 = clipVertices(vertices[index + 2], nV2);
  59750. }
  59751. if (nV1 && nV2 && nV3 && nV4) {
  59752. result.push(nV1.clone());
  59753. result.push(nV2.clone());
  59754. result.push(nV3);
  59755. result.push(nV4);
  59756. result.push(nV3.clone());
  59757. result.push(nV2.clone());
  59758. }
  59759. break;
  59760. case 2:
  59761. if (!v1Out) {
  59762. nV1 = vertices[index].clone();
  59763. nV2 = clipVertices(nV1, vertices[index + 1]);
  59764. nV3 = clipVertices(nV1, vertices[index + 2]);
  59765. result.push(nV1);
  59766. result.push(nV2);
  59767. result.push(nV3);
  59768. }
  59769. if (!v2Out) {
  59770. nV1 = vertices[index + 1].clone();
  59771. nV2 = clipVertices(nV1, vertices[index + 2]);
  59772. nV3 = clipVertices(nV1, vertices[index]);
  59773. result.push(nV1);
  59774. result.push(nV2);
  59775. result.push(nV3);
  59776. }
  59777. if (!v3Out) {
  59778. nV1 = vertices[index + 2].clone();
  59779. nV2 = clipVertices(nV1, vertices[index]);
  59780. nV3 = clipVertices(nV1, vertices[index + 1]);
  59781. result.push(nV1);
  59782. result.push(nV2);
  59783. result.push(nV3);
  59784. }
  59785. break;
  59786. case 3:
  59787. break;
  59788. }
  59789. }
  59790. return result;
  59791. };
  59792. for (var index = 0; index < indices.length; index += 3) {
  59793. var faceVertices = new Array();
  59794. faceVertices.push(extractDecalVector3(index));
  59795. faceVertices.push(extractDecalVector3(index + 1));
  59796. faceVertices.push(extractDecalVector3(index + 2));
  59797. // Clip
  59798. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  59799. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  59800. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  59801. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  59802. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  59803. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  59804. if (faceVertices.length === 0) {
  59805. continue;
  59806. }
  59807. // Add UVs and get back to world
  59808. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  59809. var vertex = faceVertices[vIndex];
  59810. //TODO check for Int32Array | Uint32Array | Uint16Array
  59811. vertexData.indices.push(currentVertexDataIndex);
  59812. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  59813. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  59814. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  59815. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  59816. currentVertexDataIndex++;
  59817. }
  59818. }
  59819. // Return mesh
  59820. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  59821. vertexData.applyToMesh(decal);
  59822. decal.position = position.clone();
  59823. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  59824. return decal;
  59825. };
  59826. // Privates
  59827. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  59828. // extrusion geometry
  59829. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  59830. var tangents = path3D.getTangents();
  59831. var normals = path3D.getNormals();
  59832. var binormals = path3D.getBinormals();
  59833. var distances = path3D.getDistances();
  59834. var angle = 0;
  59835. var returnScale = function () { return scale !== null ? scale : 1; };
  59836. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  59837. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  59838. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  59839. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59840. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59841. for (var i = 0; i < curve.length; i++) {
  59842. var shapePath = new Array();
  59843. var angleStep = rotate(i, distances[i]);
  59844. var scaleRatio = scl(i, distances[i]);
  59845. for (var p = 0; p < shape.length; p++) {
  59846. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  59847. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  59848. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  59849. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  59850. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  59851. shapePath[p] = rotated;
  59852. }
  59853. shapePaths[index] = shapePath;
  59854. angle += angleStep;
  59855. index++;
  59856. }
  59857. // cap
  59858. var capPath = function (shapePath) {
  59859. var pointCap = Array();
  59860. var barycenter = BABYLON.Vector3.Zero();
  59861. var i;
  59862. for (i = 0; i < shapePath.length; i++) {
  59863. barycenter.addInPlace(shapePath[i]);
  59864. }
  59865. barycenter.scaleInPlace(1.0 / shapePath.length);
  59866. for (i = 0; i < shapePath.length; i++) {
  59867. pointCap.push(barycenter);
  59868. }
  59869. return pointCap;
  59870. };
  59871. switch (cap) {
  59872. case BABYLON.Mesh.NO_CAP:
  59873. break;
  59874. case BABYLON.Mesh.CAP_START:
  59875. shapePaths[0] = capPath(shapePaths[2]);
  59876. shapePaths[1] = shapePaths[2];
  59877. break;
  59878. case BABYLON.Mesh.CAP_END:
  59879. shapePaths[index] = shapePaths[index - 1];
  59880. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  59881. break;
  59882. case BABYLON.Mesh.CAP_ALL:
  59883. shapePaths[0] = capPath(shapePaths[2]);
  59884. shapePaths[1] = shapePaths[2];
  59885. shapePaths[index] = shapePaths[index - 1];
  59886. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  59887. break;
  59888. default:
  59889. break;
  59890. }
  59891. return shapePaths;
  59892. };
  59893. var path3D;
  59894. var pathArray;
  59895. if (instance) {
  59896. path3D = (instance.path3D).update(curve);
  59897. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  59898. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  59899. return instance;
  59900. }
  59901. // extruded shape creation
  59902. path3D = new BABYLON.Path3D(curve);
  59903. var newShapePaths = new Array();
  59904. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59905. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  59906. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  59907. extrudedGeneric.pathArray = pathArray;
  59908. extrudedGeneric.path3D = path3D;
  59909. extrudedGeneric.cap = cap;
  59910. return extrudedGeneric;
  59911. };
  59912. return MeshBuilder;
  59913. }());
  59914. BABYLON.MeshBuilder = MeshBuilder;
  59915. })(BABYLON || (BABYLON = {}));
  59916. //# sourceMappingURL=babylon.meshBuilder.js.map
  59917. "use strict";
  59918. var BABYLON;
  59919. (function (BABYLON) {
  59920. /**
  59921. * Draco compression (https://google.github.io/draco/)
  59922. */
  59923. var DracoCompression = /** @class */ (function () {
  59924. /**
  59925. * Constructor
  59926. * @param numWorkers The number of workers for async operations
  59927. */
  59928. function DracoCompression(numWorkers) {
  59929. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  59930. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  59931. if (!workerBlobUrl || !Worker) {
  59932. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  59933. return;
  59934. }
  59935. var workers = new Array(numWorkers);
  59936. for (var i = 0; i < workers.length; i++) {
  59937. var worker = new Worker(workerBlobUrl);
  59938. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  59939. workers[i] = worker;
  59940. }
  59941. this._workerPool = new BABYLON.WorkerPool(workers);
  59942. }
  59943. /**
  59944. * Stop all async operations and release resources.
  59945. */
  59946. DracoCompression.prototype.dispose = function () {
  59947. this._workerPool.dispose();
  59948. delete this._workerPool;
  59949. };
  59950. /**
  59951. * Decode Draco compressed mesh data to vertex data.
  59952. * @param data The array buffer view for the Draco compression data
  59953. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  59954. * @returns A promise that resolves with the decoded vertex data
  59955. */
  59956. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  59957. var _this = this;
  59958. return new Promise(function (resolve, reject) {
  59959. _this._workerPool.push(function (worker, onComplete) {
  59960. var vertexData = new BABYLON.VertexData();
  59961. var onError = function (error) {
  59962. worker.removeEventListener("error", onError);
  59963. worker.removeEventListener("message", onMessage);
  59964. reject(error);
  59965. onComplete();
  59966. };
  59967. var onMessage = function (message) {
  59968. if (message.data === "done") {
  59969. worker.removeEventListener("error", onError);
  59970. worker.removeEventListener("message", onMessage);
  59971. resolve(vertexData);
  59972. onComplete();
  59973. }
  59974. else if (message.data.id === "indices") {
  59975. vertexData.indices = message.data.value;
  59976. }
  59977. else {
  59978. vertexData.set(message.data.value, message.data.id);
  59979. }
  59980. };
  59981. worker.addEventListener("error", onError);
  59982. worker.addEventListener("message", onMessage);
  59983. var dataCopy = new Uint8Array(data.byteLength);
  59984. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  59985. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  59986. });
  59987. });
  59988. };
  59989. /**
  59990. * The worker function that gets converted to a blob url to pass into a worker.
  59991. */
  59992. DracoCompression._Worker = function () {
  59993. // self is actually a DedicatedWorkerGlobalScope
  59994. var _self = self;
  59995. var decodeMesh = function (data, attributes) {
  59996. var dracoModule = new DracoDecoderModule();
  59997. var buffer = new dracoModule.DecoderBuffer();
  59998. buffer.Init(data, data.byteLength);
  59999. var decoder = new dracoModule.Decoder();
  60000. var geometry;
  60001. var status;
  60002. try {
  60003. var type = decoder.GetEncodedGeometryType(buffer);
  60004. switch (type) {
  60005. case dracoModule.TRIANGULAR_MESH:
  60006. geometry = new dracoModule.Mesh();
  60007. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60008. break;
  60009. case dracoModule.POINT_CLOUD:
  60010. geometry = new dracoModule.PointCloud();
  60011. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60012. break;
  60013. default:
  60014. throw new Error("Invalid geometry type " + type);
  60015. }
  60016. if (!status.ok() || !geometry.ptr) {
  60017. throw new Error(status.error_msg());
  60018. }
  60019. var numPoints = geometry.num_points();
  60020. if (type === dracoModule.TRIANGULAR_MESH) {
  60021. var numFaces = geometry.num_faces();
  60022. var faceIndices = new dracoModule.DracoInt32Array();
  60023. try {
  60024. var indices = new Uint32Array(numFaces * 3);
  60025. for (var i = 0; i < numFaces; i++) {
  60026. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60027. var offset = i * 3;
  60028. indices[offset + 0] = faceIndices.GetValue(0);
  60029. indices[offset + 1] = faceIndices.GetValue(1);
  60030. indices[offset + 2] = faceIndices.GetValue(2);
  60031. }
  60032. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  60033. }
  60034. finally {
  60035. dracoModule.destroy(faceIndices);
  60036. }
  60037. }
  60038. for (var kind in attributes) {
  60039. var uniqueId = attributes[kind];
  60040. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60041. var dracoData = new dracoModule.DracoFloat32Array();
  60042. try {
  60043. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60044. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60045. for (var i = 0; i < babylonData.length; i++) {
  60046. babylonData[i] = dracoData.GetValue(i);
  60047. }
  60048. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  60049. }
  60050. finally {
  60051. dracoModule.destroy(dracoData);
  60052. }
  60053. }
  60054. }
  60055. finally {
  60056. if (geometry) {
  60057. dracoModule.destroy(geometry);
  60058. }
  60059. dracoModule.destroy(decoder);
  60060. dracoModule.destroy(buffer);
  60061. }
  60062. _self.postMessage("done");
  60063. };
  60064. _self.onmessage = function (event) {
  60065. switch (event.data.id) {
  60066. case "initDecoder": {
  60067. importScripts(event.data.url);
  60068. break;
  60069. }
  60070. case "decodeMesh": {
  60071. decodeMesh(event.data.data, event.data.attributes);
  60072. break;
  60073. }
  60074. }
  60075. };
  60076. };
  60077. DracoCompression._GetDefaultDecoderUrl = function () {
  60078. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60079. return null;
  60080. }
  60081. for (var i = 0; i < document.scripts.length; i++) {
  60082. if (document.scripts[i].type === "text/x-draco-decoder") {
  60083. return document.scripts[i].src;
  60084. }
  60085. }
  60086. return null;
  60087. };
  60088. /**
  60089. * Gets the url to the draco decoder if available.
  60090. */
  60091. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  60092. return DracoCompression;
  60093. }());
  60094. BABYLON.DracoCompression = DracoCompression;
  60095. })(BABYLON || (BABYLON = {}));
  60096. //# sourceMappingURL=babylon.dracoCompression.js.map
  60097. "use strict";
  60098. var BABYLON;
  60099. (function (BABYLON) {
  60100. var AudioEngine = /** @class */ (function () {
  60101. function AudioEngine() {
  60102. this._audioContext = null;
  60103. this._audioContextInitialized = false;
  60104. this.canUseWebAudio = false;
  60105. this.WarnedWebAudioUnsupported = false;
  60106. this.unlocked = false;
  60107. this.isMP3supported = false;
  60108. this.isOGGsupported = false;
  60109. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60110. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60111. this.canUseWebAudio = true;
  60112. }
  60113. var audioElem = document.createElement('audio');
  60114. try {
  60115. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60116. this.isMP3supported = true;
  60117. }
  60118. }
  60119. catch (e) {
  60120. // protect error during capability check.
  60121. }
  60122. try {
  60123. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60124. this.isOGGsupported = true;
  60125. }
  60126. }
  60127. catch (e) {
  60128. // protect error during capability check.
  60129. }
  60130. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60131. this._unlockiOSaudio();
  60132. }
  60133. else {
  60134. this.unlocked = true;
  60135. }
  60136. }
  60137. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60138. get: function () {
  60139. if (!this._audioContextInitialized) {
  60140. this._initializeAudioContext();
  60141. }
  60142. return this._audioContext;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. AudioEngine.prototype._unlockiOSaudio = function () {
  60148. var _this = this;
  60149. var unlockaudio = function () {
  60150. if (!_this.audioContext) {
  60151. return;
  60152. }
  60153. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60154. var source = _this.audioContext.createBufferSource();
  60155. source.buffer = buffer;
  60156. source.connect(_this.audioContext.destination);
  60157. source.start(0);
  60158. setTimeout(function () {
  60159. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60160. _this.unlocked = true;
  60161. window.removeEventListener('touchend', unlockaudio, false);
  60162. if (_this.onAudioUnlocked) {
  60163. _this.onAudioUnlocked();
  60164. }
  60165. }
  60166. }, 0);
  60167. };
  60168. window.addEventListener('touchend', unlockaudio, false);
  60169. };
  60170. AudioEngine.prototype._initializeAudioContext = function () {
  60171. try {
  60172. if (this.canUseWebAudio) {
  60173. this._audioContext = new AudioContext();
  60174. // create a global volume gain node
  60175. this.masterGain = this._audioContext.createGain();
  60176. this.masterGain.gain.value = 1;
  60177. this.masterGain.connect(this._audioContext.destination);
  60178. this._audioContextInitialized = true;
  60179. }
  60180. }
  60181. catch (e) {
  60182. this.canUseWebAudio = false;
  60183. BABYLON.Tools.Error("Web Audio: " + e.message);
  60184. }
  60185. };
  60186. AudioEngine.prototype.dispose = function () {
  60187. if (this.canUseWebAudio && this._audioContextInitialized) {
  60188. if (this._connectedAnalyser && this._audioContext) {
  60189. this._connectedAnalyser.stopDebugCanvas();
  60190. this._connectedAnalyser.dispose();
  60191. this.masterGain.disconnect();
  60192. this.masterGain.connect(this._audioContext.destination);
  60193. this._connectedAnalyser = null;
  60194. }
  60195. this.masterGain.gain.value = 1;
  60196. }
  60197. this.WarnedWebAudioUnsupported = false;
  60198. };
  60199. AudioEngine.prototype.getGlobalVolume = function () {
  60200. if (this.canUseWebAudio && this._audioContextInitialized) {
  60201. return this.masterGain.gain.value;
  60202. }
  60203. else {
  60204. return -1;
  60205. }
  60206. };
  60207. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60208. if (this.canUseWebAudio && this._audioContextInitialized) {
  60209. this.masterGain.gain.value = newVolume;
  60210. }
  60211. };
  60212. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60213. if (this._connectedAnalyser) {
  60214. this._connectedAnalyser.stopDebugCanvas();
  60215. }
  60216. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60217. this._connectedAnalyser = analyser;
  60218. this.masterGain.disconnect();
  60219. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60220. }
  60221. };
  60222. return AudioEngine;
  60223. }());
  60224. BABYLON.AudioEngine = AudioEngine;
  60225. })(BABYLON || (BABYLON = {}));
  60226. //# sourceMappingURL=babylon.audioEngine.js.map
  60227. "use strict";
  60228. var BABYLON;
  60229. (function (BABYLON) {
  60230. var Sound = /** @class */ (function () {
  60231. /**
  60232. * Create a sound and attach it to a scene
  60233. * @param name Name of your sound
  60234. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60235. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60236. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60237. */
  60238. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60239. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60240. var _this = this;
  60241. this.autoplay = false;
  60242. this.loop = false;
  60243. this.useCustomAttenuation = false;
  60244. this.spatialSound = false;
  60245. this.refDistance = 1;
  60246. this.rolloffFactor = 1;
  60247. this.maxDistance = 100;
  60248. this.distanceModel = "linear";
  60249. this._panningModel = "equalpower";
  60250. this._playbackRate = 1;
  60251. this._streaming = false;
  60252. this._startTime = 0;
  60253. this._startOffset = 0;
  60254. this._position = BABYLON.Vector3.Zero();
  60255. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60256. this._volume = 1;
  60257. this._isReadyToPlay = false;
  60258. this.isPlaying = false;
  60259. this.isPaused = false;
  60260. this._isDirectional = false;
  60261. // Used if you'd like to create a directional sound.
  60262. // If not set, the sound will be omnidirectional
  60263. this._coneInnerAngle = 360;
  60264. this._coneOuterAngle = 360;
  60265. this._coneOuterGain = 0;
  60266. this._isOutputConnected = false;
  60267. this._urlType = "Unknown";
  60268. this.name = name;
  60269. this._scene = scene;
  60270. this._readyToPlayCallback = readyToPlayCallback;
  60271. // Default custom attenuation function is a linear attenuation
  60272. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60273. if (currentDistance < maxDistance) {
  60274. return currentVolume * (1 - currentDistance / maxDistance);
  60275. }
  60276. else {
  60277. return 0;
  60278. }
  60279. };
  60280. if (options) {
  60281. this.autoplay = options.autoplay || false;
  60282. this.loop = options.loop || false;
  60283. // if volume === 0, we need another way to check this option
  60284. if (options.volume !== undefined) {
  60285. this._volume = options.volume;
  60286. }
  60287. this.spatialSound = options.spatialSound || false;
  60288. this.maxDistance = options.maxDistance || 100;
  60289. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60290. this.rolloffFactor = options.rolloffFactor || 1;
  60291. this.refDistance = options.refDistance || 1;
  60292. this.distanceModel = options.distanceModel || "linear";
  60293. this._playbackRate = options.playbackRate || 1;
  60294. this._streaming = options.streaming || false;
  60295. }
  60296. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60297. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60298. this._soundGain.gain.value = this._volume;
  60299. this._inputAudioNode = this._soundGain;
  60300. this._ouputAudioNode = this._soundGain;
  60301. if (this.spatialSound) {
  60302. this._createSpatialParameters();
  60303. }
  60304. this._scene.mainSoundTrack.AddSound(this);
  60305. var validParameter = true;
  60306. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60307. if (urlOrArrayBuffer) {
  60308. try {
  60309. if (typeof (urlOrArrayBuffer) === "string")
  60310. this._urlType = "String";
  60311. if (Array.isArray(urlOrArrayBuffer))
  60312. this._urlType = "Array";
  60313. if (urlOrArrayBuffer instanceof ArrayBuffer)
  60314. this._urlType = "ArrayBuffer";
  60315. var urls = [];
  60316. var codecSupportedFound = false;
  60317. switch (this._urlType) {
  60318. case "ArrayBuffer":
  60319. if (urlOrArrayBuffer.byteLength > 0) {
  60320. codecSupportedFound = true;
  60321. this._soundLoaded(urlOrArrayBuffer);
  60322. }
  60323. break;
  60324. case "String":
  60325. urls.push(urlOrArrayBuffer);
  60326. case "Array":
  60327. if (urls.length === 0)
  60328. urls = urlOrArrayBuffer;
  60329. // If we found a supported format, we load it immediately and stop the loop
  60330. for (var i = 0; i < urls.length; i++) {
  60331. var url = urls[i];
  60332. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  60333. codecSupportedFound = true;
  60334. }
  60335. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  60336. codecSupportedFound = true;
  60337. }
  60338. if (url.indexOf(".wav", url.length - 4) !== -1) {
  60339. codecSupportedFound = true;
  60340. }
  60341. if (url.indexOf("blob:") !== -1) {
  60342. codecSupportedFound = true;
  60343. }
  60344. if (codecSupportedFound) {
  60345. // Loading sound using XHR2
  60346. if (!this._streaming) {
  60347. this._scene._loadFile(url, function (data) {
  60348. _this._soundLoaded(data);
  60349. }, undefined, true, true, function (exception) {
  60350. if (exception) {
  60351. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  60352. }
  60353. BABYLON.Tools.Error("Sound creation aborted.");
  60354. _this._scene.mainSoundTrack.RemoveSound(_this);
  60355. });
  60356. }
  60357. else {
  60358. this._htmlAudioElement = new Audio(url);
  60359. this._htmlAudioElement.controls = false;
  60360. this._htmlAudioElement.loop = this.loop;
  60361. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  60362. this._htmlAudioElement.preload = "auto";
  60363. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  60364. _this._isReadyToPlay = true;
  60365. if (_this.autoplay) {
  60366. _this.play();
  60367. }
  60368. if (_this._readyToPlayCallback) {
  60369. _this._readyToPlayCallback();
  60370. }
  60371. });
  60372. document.body.appendChild(this._htmlAudioElement);
  60373. }
  60374. break;
  60375. }
  60376. }
  60377. break;
  60378. default:
  60379. validParameter = false;
  60380. break;
  60381. }
  60382. if (!validParameter) {
  60383. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  60384. }
  60385. else {
  60386. if (!codecSupportedFound) {
  60387. this._isReadyToPlay = true;
  60388. // Simulating a ready to play event to avoid breaking code path
  60389. if (this._readyToPlayCallback) {
  60390. window.setTimeout(function () {
  60391. if (_this._readyToPlayCallback) {
  60392. _this._readyToPlayCallback();
  60393. }
  60394. }, 1000);
  60395. }
  60396. }
  60397. }
  60398. }
  60399. catch (ex) {
  60400. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  60401. this._scene.mainSoundTrack.RemoveSound(this);
  60402. }
  60403. }
  60404. }
  60405. else {
  60406. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  60407. this._scene.mainSoundTrack.AddSound(this);
  60408. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  60409. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  60410. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  60411. }
  60412. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  60413. if (this._readyToPlayCallback) {
  60414. window.setTimeout(function () {
  60415. if (_this._readyToPlayCallback) {
  60416. _this._readyToPlayCallback();
  60417. }
  60418. }, 1000);
  60419. }
  60420. }
  60421. }
  60422. Sound.prototype.dispose = function () {
  60423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60424. if (this.isPlaying) {
  60425. this.stop();
  60426. }
  60427. this._isReadyToPlay = false;
  60428. if (this.soundTrackId === -1) {
  60429. this._scene.mainSoundTrack.RemoveSound(this);
  60430. }
  60431. else {
  60432. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  60433. }
  60434. if (this._soundGain) {
  60435. this._soundGain.disconnect();
  60436. this._soundGain = null;
  60437. }
  60438. if (this._soundPanner) {
  60439. this._soundPanner.disconnect();
  60440. this._soundPanner = null;
  60441. }
  60442. if (this._soundSource) {
  60443. this._soundSource.disconnect();
  60444. this._soundSource = null;
  60445. }
  60446. this._audioBuffer = null;
  60447. if (this._htmlAudioElement) {
  60448. this._htmlAudioElement.pause();
  60449. this._htmlAudioElement.src = "";
  60450. document.body.removeChild(this._htmlAudioElement);
  60451. }
  60452. if (this._connectedMesh && this._registerFunc) {
  60453. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60454. this._connectedMesh = null;
  60455. }
  60456. }
  60457. };
  60458. Sound.prototype.isReady = function () {
  60459. return this._isReadyToPlay;
  60460. };
  60461. Sound.prototype._soundLoaded = function (audioData) {
  60462. var _this = this;
  60463. if (!BABYLON.Engine.audioEngine.audioContext) {
  60464. return;
  60465. }
  60466. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  60467. _this._audioBuffer = buffer;
  60468. _this._isReadyToPlay = true;
  60469. if (_this.autoplay) {
  60470. _this.play();
  60471. }
  60472. if (_this._readyToPlayCallback) {
  60473. _this._readyToPlayCallback();
  60474. }
  60475. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  60476. };
  60477. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  60478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60479. this._audioBuffer = audioBuffer;
  60480. this._isReadyToPlay = true;
  60481. }
  60482. };
  60483. Sound.prototype.updateOptions = function (options) {
  60484. if (options) {
  60485. this.loop = options.loop || this.loop;
  60486. this.maxDistance = options.maxDistance || this.maxDistance;
  60487. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  60488. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  60489. this.refDistance = options.refDistance || this.refDistance;
  60490. this.distanceModel = options.distanceModel || this.distanceModel;
  60491. this._playbackRate = options.playbackRate || this._playbackRate;
  60492. this._updateSpatialParameters();
  60493. if (this.isPlaying) {
  60494. if (this._streaming) {
  60495. this._htmlAudioElement.playbackRate = this._playbackRate;
  60496. }
  60497. else {
  60498. if (this._soundSource) {
  60499. this._soundSource.playbackRate.value = this._playbackRate;
  60500. }
  60501. }
  60502. }
  60503. }
  60504. };
  60505. Sound.prototype._createSpatialParameters = function () {
  60506. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60507. if (this._scene.headphone) {
  60508. this._panningModel = "HRTF";
  60509. }
  60510. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  60511. this._updateSpatialParameters();
  60512. this._soundPanner.connect(this._ouputAudioNode);
  60513. this._inputAudioNode = this._soundPanner;
  60514. }
  60515. };
  60516. Sound.prototype._updateSpatialParameters = function () {
  60517. if (this.spatialSound && this._soundPanner) {
  60518. if (this.useCustomAttenuation) {
  60519. // Tricks to disable in a way embedded Web Audio attenuation
  60520. this._soundPanner.distanceModel = "linear";
  60521. this._soundPanner.maxDistance = Number.MAX_VALUE;
  60522. this._soundPanner.refDistance = 1;
  60523. this._soundPanner.rolloffFactor = 1;
  60524. this._soundPanner.panningModel = this._panningModel;
  60525. }
  60526. else {
  60527. this._soundPanner.distanceModel = this.distanceModel;
  60528. this._soundPanner.maxDistance = this.maxDistance;
  60529. this._soundPanner.refDistance = this.refDistance;
  60530. this._soundPanner.rolloffFactor = this.rolloffFactor;
  60531. this._soundPanner.panningModel = this._panningModel;
  60532. }
  60533. }
  60534. };
  60535. Sound.prototype.switchPanningModelToHRTF = function () {
  60536. this._panningModel = "HRTF";
  60537. this._switchPanningModel();
  60538. };
  60539. Sound.prototype.switchPanningModelToEqualPower = function () {
  60540. this._panningModel = "equalpower";
  60541. this._switchPanningModel();
  60542. };
  60543. Sound.prototype._switchPanningModel = function () {
  60544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60545. this._soundPanner.panningModel = this._panningModel;
  60546. }
  60547. };
  60548. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  60549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60550. if (this._isOutputConnected) {
  60551. this._ouputAudioNode.disconnect();
  60552. }
  60553. this._ouputAudioNode.connect(soundTrackAudioNode);
  60554. this._isOutputConnected = true;
  60555. }
  60556. };
  60557. /**
  60558. * Transform this sound into a directional source
  60559. * @param coneInnerAngle Size of the inner cone in degree
  60560. * @param coneOuterAngle Size of the outer cone in degree
  60561. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  60562. */
  60563. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  60564. if (coneOuterAngle < coneInnerAngle) {
  60565. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  60566. return;
  60567. }
  60568. this._coneInnerAngle = coneInnerAngle;
  60569. this._coneOuterAngle = coneOuterAngle;
  60570. this._coneOuterGain = coneOuterGain;
  60571. this._isDirectional = true;
  60572. if (this.isPlaying && this.loop) {
  60573. this.stop();
  60574. this.play();
  60575. }
  60576. };
  60577. Sound.prototype.setPosition = function (newPosition) {
  60578. this._position = newPosition;
  60579. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60580. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60581. }
  60582. };
  60583. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  60584. this._localDirection = newLocalDirection;
  60585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  60586. this._updateDirection();
  60587. }
  60588. };
  60589. Sound.prototype._updateDirection = function () {
  60590. if (!this._connectedMesh || !this._soundPanner) {
  60591. return;
  60592. }
  60593. var mat = this._connectedMesh.getWorldMatrix();
  60594. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  60595. direction.normalize();
  60596. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  60597. };
  60598. Sound.prototype.updateDistanceFromListener = function () {
  60599. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  60600. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  60601. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  60602. }
  60603. };
  60604. Sound.prototype.setAttenuationFunction = function (callback) {
  60605. this._customAttenuationFunction = callback;
  60606. };
  60607. /**
  60608. * Play the sound
  60609. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  60610. * @param offset (optional) Start the sound setting it at a specific time
  60611. */
  60612. Sound.prototype.play = function (time, offset) {
  60613. var _this = this;
  60614. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  60615. try {
  60616. if (this._startOffset < 0) {
  60617. time = -this._startOffset;
  60618. this._startOffset = 0;
  60619. }
  60620. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60621. if (!this._soundSource || !this._streamingSource) {
  60622. if (this.spatialSound && this._soundPanner) {
  60623. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60624. if (this._isDirectional) {
  60625. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  60626. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  60627. this._soundPanner.coneOuterGain = this._coneOuterGain;
  60628. if (this._connectedMesh) {
  60629. this._updateDirection();
  60630. }
  60631. else {
  60632. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  60633. }
  60634. }
  60635. }
  60636. }
  60637. if (this._streaming) {
  60638. if (!this._streamingSource) {
  60639. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  60640. this._htmlAudioElement.onended = function () { _this._onended(); };
  60641. this._htmlAudioElement.playbackRate = this._playbackRate;
  60642. }
  60643. this._streamingSource.disconnect();
  60644. this._streamingSource.connect(this._inputAudioNode);
  60645. this._htmlAudioElement.play();
  60646. }
  60647. else {
  60648. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  60649. this._soundSource.buffer = this._audioBuffer;
  60650. this._soundSource.connect(this._inputAudioNode);
  60651. this._soundSource.loop = this.loop;
  60652. this._soundSource.playbackRate.value = this._playbackRate;
  60653. this._soundSource.onended = function () { _this._onended(); };
  60654. if (this._soundSource.buffer) {
  60655. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  60656. }
  60657. }
  60658. this._startTime = startTime;
  60659. this.isPlaying = true;
  60660. this.isPaused = false;
  60661. }
  60662. catch (ex) {
  60663. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  60664. }
  60665. }
  60666. };
  60667. Sound.prototype._onended = function () {
  60668. this.isPlaying = false;
  60669. if (this.onended) {
  60670. this.onended();
  60671. }
  60672. };
  60673. /**
  60674. * Stop the sound
  60675. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  60676. */
  60677. Sound.prototype.stop = function (time) {
  60678. if (this.isPlaying) {
  60679. if (this._streaming) {
  60680. this._htmlAudioElement.pause();
  60681. // Test needed for Firefox or it will generate an Invalid State Error
  60682. if (this._htmlAudioElement.currentTime > 0) {
  60683. this._htmlAudioElement.currentTime = 0;
  60684. }
  60685. }
  60686. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  60687. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60688. this._soundSource.stop(stopTime);
  60689. this._soundSource.onended = function () { };
  60690. if (!this.isPaused) {
  60691. this._startOffset = 0;
  60692. }
  60693. }
  60694. this.isPlaying = false;
  60695. }
  60696. };
  60697. Sound.prototype.pause = function () {
  60698. if (this.isPlaying) {
  60699. this.isPaused = true;
  60700. if (this._streaming) {
  60701. this._htmlAudioElement.pause();
  60702. }
  60703. else if (BABYLON.Engine.audioEngine.audioContext) {
  60704. this.stop(0);
  60705. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  60706. }
  60707. }
  60708. };
  60709. Sound.prototype.setVolume = function (newVolume, time) {
  60710. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  60711. if (time && BABYLON.Engine.audioEngine.audioContext) {
  60712. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  60713. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  60714. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  60715. }
  60716. else {
  60717. this._soundGain.gain.value = newVolume;
  60718. }
  60719. }
  60720. this._volume = newVolume;
  60721. };
  60722. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  60723. this._playbackRate = newPlaybackRate;
  60724. if (this.isPlaying) {
  60725. if (this._streaming) {
  60726. this._htmlAudioElement.playbackRate = this._playbackRate;
  60727. }
  60728. else if (this._soundSource) {
  60729. this._soundSource.playbackRate.value = this._playbackRate;
  60730. }
  60731. }
  60732. };
  60733. Sound.prototype.getVolume = function () {
  60734. return this._volume;
  60735. };
  60736. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  60737. var _this = this;
  60738. if (this._connectedMesh && this._registerFunc) {
  60739. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60740. this._registerFunc = null;
  60741. }
  60742. this._connectedMesh = meshToConnectTo;
  60743. if (!this.spatialSound) {
  60744. this.spatialSound = true;
  60745. this._createSpatialParameters();
  60746. if (this.isPlaying && this.loop) {
  60747. this.stop();
  60748. this.play();
  60749. }
  60750. }
  60751. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  60752. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  60753. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  60754. };
  60755. Sound.prototype.detachFromMesh = function () {
  60756. if (this._connectedMesh && this._registerFunc) {
  60757. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60758. this._registerFunc = null;
  60759. this._connectedMesh = null;
  60760. }
  60761. };
  60762. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  60763. if (!node.getBoundingInfo) {
  60764. return;
  60765. }
  60766. var mesh = node;
  60767. var boundingInfo = mesh.getBoundingInfo();
  60768. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  60769. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  60770. this._updateDirection();
  60771. }
  60772. };
  60773. Sound.prototype.clone = function () {
  60774. var _this = this;
  60775. if (!this._streaming) {
  60776. var setBufferAndRun = function () {
  60777. if (_this._isReadyToPlay) {
  60778. clonedSound._audioBuffer = _this.getAudioBuffer();
  60779. clonedSound._isReadyToPlay = true;
  60780. if (clonedSound.autoplay) {
  60781. clonedSound.play();
  60782. }
  60783. }
  60784. else {
  60785. window.setTimeout(setBufferAndRun, 300);
  60786. }
  60787. };
  60788. var currentOptions = {
  60789. autoplay: this.autoplay, loop: this.loop,
  60790. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  60791. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  60792. refDistance: this.refDistance, distanceModel: this.distanceModel
  60793. };
  60794. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  60795. if (this.useCustomAttenuation) {
  60796. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  60797. }
  60798. clonedSound.setPosition(this._position);
  60799. clonedSound.setPlaybackRate(this._playbackRate);
  60800. setBufferAndRun();
  60801. return clonedSound;
  60802. }
  60803. else {
  60804. return null;
  60805. }
  60806. };
  60807. Sound.prototype.getAudioBuffer = function () {
  60808. return this._audioBuffer;
  60809. };
  60810. Sound.prototype.serialize = function () {
  60811. var serializationObject = {
  60812. name: this.name,
  60813. url: this.name,
  60814. autoplay: this.autoplay,
  60815. loop: this.loop,
  60816. volume: this._volume,
  60817. spatialSound: this.spatialSound,
  60818. maxDistance: this.maxDistance,
  60819. rolloffFactor: this.rolloffFactor,
  60820. refDistance: this.refDistance,
  60821. distanceModel: this.distanceModel,
  60822. playbackRate: this._playbackRate,
  60823. panningModel: this._panningModel,
  60824. soundTrackId: this.soundTrackId
  60825. };
  60826. if (this.spatialSound) {
  60827. if (this._connectedMesh)
  60828. serializationObject.connectedMeshId = this._connectedMesh.id;
  60829. serializationObject.position = this._position.asArray();
  60830. serializationObject.refDistance = this.refDistance;
  60831. serializationObject.distanceModel = this.distanceModel;
  60832. serializationObject.isDirectional = this._isDirectional;
  60833. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  60834. serializationObject.coneInnerAngle = this._coneInnerAngle;
  60835. serializationObject.coneOuterAngle = this._coneOuterAngle;
  60836. serializationObject.coneOuterGain = this._coneOuterGain;
  60837. }
  60838. return serializationObject;
  60839. };
  60840. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  60841. var soundName = parsedSound.name;
  60842. var soundUrl;
  60843. if (parsedSound.url) {
  60844. soundUrl = rootUrl + parsedSound.url;
  60845. }
  60846. else {
  60847. soundUrl = rootUrl + soundName;
  60848. }
  60849. var options = {
  60850. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  60851. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  60852. rolloffFactor: parsedSound.rolloffFactor,
  60853. refDistance: parsedSound.refDistance,
  60854. distanceModel: parsedSound.distanceModel,
  60855. playbackRate: parsedSound.playbackRate
  60856. };
  60857. var newSound;
  60858. if (!sourceSound) {
  60859. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  60860. scene._addPendingData(newSound);
  60861. }
  60862. else {
  60863. var setBufferAndRun = function () {
  60864. if (sourceSound._isReadyToPlay) {
  60865. newSound._audioBuffer = sourceSound.getAudioBuffer();
  60866. newSound._isReadyToPlay = true;
  60867. if (newSound.autoplay) {
  60868. newSound.play();
  60869. }
  60870. }
  60871. else {
  60872. window.setTimeout(setBufferAndRun, 300);
  60873. }
  60874. };
  60875. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  60876. setBufferAndRun();
  60877. }
  60878. if (parsedSound.position) {
  60879. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  60880. newSound.setPosition(soundPosition);
  60881. }
  60882. if (parsedSound.isDirectional) {
  60883. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  60884. if (parsedSound.localDirectionToMesh) {
  60885. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  60886. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  60887. }
  60888. }
  60889. if (parsedSound.connectedMeshId) {
  60890. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  60891. if (connectedMesh) {
  60892. newSound.attachToMesh(connectedMesh);
  60893. }
  60894. }
  60895. return newSound;
  60896. };
  60897. return Sound;
  60898. }());
  60899. BABYLON.Sound = Sound;
  60900. })(BABYLON || (BABYLON = {}));
  60901. //# sourceMappingURL=babylon.sound.js.map
  60902. "use strict";
  60903. var BABYLON;
  60904. (function (BABYLON) {
  60905. var SoundTrack = /** @class */ (function () {
  60906. function SoundTrack(scene, options) {
  60907. this.id = -1;
  60908. this._isMainTrack = false;
  60909. this._isInitialized = false;
  60910. this._scene = scene;
  60911. this.soundCollection = new Array();
  60912. this._options = options;
  60913. if (!this._isMainTrack) {
  60914. this._scene.soundTracks.push(this);
  60915. this.id = this._scene.soundTracks.length - 1;
  60916. }
  60917. }
  60918. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  60919. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60920. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  60921. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  60922. if (this._options) {
  60923. if (this._options.volume) {
  60924. this._outputAudioNode.gain.value = this._options.volume;
  60925. }
  60926. if (this._options.mainTrack) {
  60927. this._isMainTrack = this._options.mainTrack;
  60928. }
  60929. }
  60930. this._isInitialized = true;
  60931. }
  60932. };
  60933. SoundTrack.prototype.dispose = function () {
  60934. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60935. if (this._connectedAnalyser) {
  60936. this._connectedAnalyser.stopDebugCanvas();
  60937. }
  60938. while (this.soundCollection.length) {
  60939. this.soundCollection[0].dispose();
  60940. }
  60941. if (this._outputAudioNode) {
  60942. this._outputAudioNode.disconnect();
  60943. }
  60944. this._outputAudioNode = null;
  60945. }
  60946. };
  60947. SoundTrack.prototype.AddSound = function (sound) {
  60948. if (!this._isInitialized) {
  60949. this._initializeSoundTrackAudioGraph();
  60950. }
  60951. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60952. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  60953. }
  60954. if (sound.soundTrackId) {
  60955. if (sound.soundTrackId === -1) {
  60956. this._scene.mainSoundTrack.RemoveSound(sound);
  60957. }
  60958. else {
  60959. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  60960. }
  60961. }
  60962. this.soundCollection.push(sound);
  60963. sound.soundTrackId = this.id;
  60964. };
  60965. SoundTrack.prototype.RemoveSound = function (sound) {
  60966. var index = this.soundCollection.indexOf(sound);
  60967. if (index !== -1) {
  60968. this.soundCollection.splice(index, 1);
  60969. }
  60970. };
  60971. SoundTrack.prototype.setVolume = function (newVolume) {
  60972. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60973. this._outputAudioNode.gain.value = newVolume;
  60974. }
  60975. };
  60976. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  60977. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60978. for (var i = 0; i < this.soundCollection.length; i++) {
  60979. this.soundCollection[i].switchPanningModelToHRTF();
  60980. }
  60981. }
  60982. };
  60983. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  60984. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60985. for (var i = 0; i < this.soundCollection.length; i++) {
  60986. this.soundCollection[i].switchPanningModelToEqualPower();
  60987. }
  60988. }
  60989. };
  60990. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  60991. if (this._connectedAnalyser) {
  60992. this._connectedAnalyser.stopDebugCanvas();
  60993. }
  60994. this._connectedAnalyser = analyser;
  60995. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60996. this._outputAudioNode.disconnect();
  60997. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  60998. }
  60999. };
  61000. return SoundTrack;
  61001. }());
  61002. BABYLON.SoundTrack = SoundTrack;
  61003. })(BABYLON || (BABYLON = {}));
  61004. //# sourceMappingURL=babylon.soundtrack.js.map
  61005. "use strict";
  61006. var BABYLON;
  61007. (function (BABYLON) {
  61008. var Analyser = /** @class */ (function () {
  61009. function Analyser(scene) {
  61010. this.SMOOTHING = 0.75;
  61011. this.FFT_SIZE = 512;
  61012. this.BARGRAPHAMPLITUDE = 256;
  61013. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61014. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61015. this._scene = scene;
  61016. this._audioEngine = BABYLON.Engine.audioEngine;
  61017. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61018. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61019. this._webAudioAnalyser.minDecibels = -140;
  61020. this._webAudioAnalyser.maxDecibels = 0;
  61021. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61022. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61023. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61024. }
  61025. }
  61026. Analyser.prototype.getFrequencyBinCount = function () {
  61027. if (this._audioEngine.canUseWebAudio) {
  61028. return this._webAudioAnalyser.frequencyBinCount;
  61029. }
  61030. else {
  61031. return 0;
  61032. }
  61033. };
  61034. Analyser.prototype.getByteFrequencyData = function () {
  61035. if (this._audioEngine.canUseWebAudio) {
  61036. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61037. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61038. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61039. }
  61040. return this._byteFreqs;
  61041. };
  61042. Analyser.prototype.getByteTimeDomainData = function () {
  61043. if (this._audioEngine.canUseWebAudio) {
  61044. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61045. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61046. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61047. }
  61048. return this._byteTime;
  61049. };
  61050. Analyser.prototype.getFloatFrequencyData = function () {
  61051. if (this._audioEngine.canUseWebAudio) {
  61052. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61053. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61054. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61055. }
  61056. return this._floatFreqs;
  61057. };
  61058. Analyser.prototype.drawDebugCanvas = function () {
  61059. var _this = this;
  61060. if (this._audioEngine.canUseWebAudio) {
  61061. if (!this._debugCanvas) {
  61062. this._debugCanvas = document.createElement("canvas");
  61063. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61064. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61065. this._debugCanvas.style.position = "absolute";
  61066. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61067. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61068. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61069. document.body.appendChild(this._debugCanvas);
  61070. this._registerFunc = function () {
  61071. _this.drawDebugCanvas();
  61072. };
  61073. this._scene.registerBeforeRender(this._registerFunc);
  61074. }
  61075. if (this._registerFunc && this._debugCanvasContext) {
  61076. var workingArray = this.getByteFrequencyData();
  61077. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61078. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61079. // Draw the frequency domain chart.
  61080. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61081. var value = workingArray[i];
  61082. var percent = value / this.BARGRAPHAMPLITUDE;
  61083. var height = this.DEBUGCANVASSIZE.height * percent;
  61084. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61085. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61086. var hue = i / this.getFrequencyBinCount() * 360;
  61087. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61088. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61089. }
  61090. }
  61091. }
  61092. };
  61093. Analyser.prototype.stopDebugCanvas = function () {
  61094. if (this._debugCanvas) {
  61095. if (this._registerFunc) {
  61096. this._scene.unregisterBeforeRender(this._registerFunc);
  61097. this._registerFunc = null;
  61098. }
  61099. document.body.removeChild(this._debugCanvas);
  61100. this._debugCanvas = null;
  61101. this._debugCanvasContext = null;
  61102. }
  61103. };
  61104. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61105. if (this._audioEngine.canUseWebAudio) {
  61106. inputAudioNode.connect(this._webAudioAnalyser);
  61107. this._webAudioAnalyser.connect(outputAudioNode);
  61108. }
  61109. };
  61110. Analyser.prototype.dispose = function () {
  61111. if (this._audioEngine.canUseWebAudio) {
  61112. this._webAudioAnalyser.disconnect();
  61113. }
  61114. };
  61115. return Analyser;
  61116. }());
  61117. BABYLON.Analyser = Analyser;
  61118. })(BABYLON || (BABYLON = {}));
  61119. //# sourceMappingURL=babylon.analyser.js.map
  61120. "use strict";
  61121. var BABYLON;
  61122. (function (BABYLON) {
  61123. var CubeTexture = /** @class */ (function (_super) {
  61124. __extends(CubeTexture, _super);
  61125. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61126. if (extensions === void 0) { extensions = null; }
  61127. if (noMipmap === void 0) { noMipmap = false; }
  61128. if (files === void 0) { files = null; }
  61129. if (onLoad === void 0) { onLoad = null; }
  61130. if (onError === void 0) { onError = null; }
  61131. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61132. if (prefiltered === void 0) { prefiltered = false; }
  61133. if (forcedExtension === void 0) { forcedExtension = null; }
  61134. var _this = _super.call(this, scene) || this;
  61135. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61136. /**
  61137. * Gets or sets the center of the bounding box associated with the cube texture
  61138. * It must define where the camera used to render the texture was set
  61139. */
  61140. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61141. _this.name = rootUrl;
  61142. _this.url = rootUrl;
  61143. _this._noMipmap = noMipmap;
  61144. _this.hasAlpha = false;
  61145. _this._format = format;
  61146. _this._prefiltered = prefiltered;
  61147. _this.isCube = true;
  61148. _this._textureMatrix = BABYLON.Matrix.Identity();
  61149. if (prefiltered) {
  61150. _this.gammaSpace = false;
  61151. }
  61152. if (!rootUrl && !files) {
  61153. return _this;
  61154. }
  61155. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61156. var lastDot = rootUrl.lastIndexOf(".");
  61157. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61158. var isDDS = (extension === ".dds");
  61159. if (!files) {
  61160. if (!isDDS && !extensions) {
  61161. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61162. }
  61163. files = [];
  61164. if (extensions) {
  61165. for (var index = 0; index < extensions.length; index++) {
  61166. files.push(rootUrl + extensions[index]);
  61167. }
  61168. }
  61169. }
  61170. _this._files = files;
  61171. if (!_this._texture) {
  61172. if (!scene.useDelayedTextureLoading) {
  61173. if (prefiltered) {
  61174. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61175. }
  61176. else {
  61177. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61178. }
  61179. }
  61180. else {
  61181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61182. }
  61183. }
  61184. else if (onLoad) {
  61185. if (_this._texture.isReady) {
  61186. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61187. }
  61188. else {
  61189. _this._texture.onLoadedObservable.add(onLoad);
  61190. }
  61191. }
  61192. return _this;
  61193. }
  61194. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61195. get: function () {
  61196. return this._boundingBoxSize;
  61197. },
  61198. /**
  61199. * Gets or sets the size of the bounding box associated with the cube texture
  61200. * When defined, the cubemap will switch to local mode
  61201. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61202. * @example https://www.babylonjs-playground.com/#RNASML
  61203. */
  61204. set: function (value) {
  61205. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61206. return;
  61207. }
  61208. this._boundingBoxSize = value;
  61209. var scene = this.getScene();
  61210. if (scene) {
  61211. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61212. }
  61213. },
  61214. enumerable: true,
  61215. configurable: true
  61216. });
  61217. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61218. var rootUrlKey = "";
  61219. files.forEach(function (url) { return rootUrlKey += url; });
  61220. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61221. };
  61222. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61223. if (forcedExtension === void 0) { forcedExtension = null; }
  61224. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61225. };
  61226. // Methods
  61227. CubeTexture.prototype.delayLoad = function () {
  61228. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61229. return;
  61230. }
  61231. var scene = this.getScene();
  61232. if (!scene) {
  61233. return;
  61234. }
  61235. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61236. this._texture = this._getFromCache(this.url, this._noMipmap);
  61237. if (!this._texture) {
  61238. if (this._prefiltered) {
  61239. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61240. }
  61241. else {
  61242. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61243. }
  61244. }
  61245. };
  61246. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61247. return this._textureMatrix;
  61248. };
  61249. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61250. this._textureMatrix = value;
  61251. };
  61252. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61253. var texture = BABYLON.SerializationHelper.Parse(function () {
  61254. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61255. }, parsedTexture, scene);
  61256. // Local Cubemaps
  61257. if (parsedTexture.boundingBoxPosition) {
  61258. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61259. }
  61260. if (parsedTexture.boundingBoxSize) {
  61261. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61262. }
  61263. // Animations
  61264. if (parsedTexture.animations) {
  61265. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61266. var parsedAnimation = parsedTexture.animations[animationIndex];
  61267. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61268. }
  61269. }
  61270. return texture;
  61271. };
  61272. CubeTexture.prototype.clone = function () {
  61273. var _this = this;
  61274. return BABYLON.SerializationHelper.Clone(function () {
  61275. var scene = _this.getScene();
  61276. if (!scene) {
  61277. return _this;
  61278. }
  61279. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61280. }, this);
  61281. };
  61282. return CubeTexture;
  61283. }(BABYLON.BaseTexture));
  61284. BABYLON.CubeTexture = CubeTexture;
  61285. })(BABYLON || (BABYLON = {}));
  61286. //# sourceMappingURL=babylon.cubeTexture.js.map
  61287. "use strict";
  61288. var BABYLON;
  61289. (function (BABYLON) {
  61290. var RenderTargetTexture = /** @class */ (function (_super) {
  61291. __extends(RenderTargetTexture, _super);
  61292. /**
  61293. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  61294. * or used a shadow, depth texture...
  61295. * @param name The friendly name of the texture
  61296. * @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)
  61297. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  61298. * @param generateMipMaps True if mip maps need to be generated after render.
  61299. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  61300. * @param type The type of the buffer in the RTT (int, half float, float...)
  61301. * @param isCube True if a cube texture needs to be created
  61302. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  61303. * @param generateDepthBuffer True to generate a depth buffer
  61304. * @param generateStencilBuffer True to generate a stencil buffer
  61305. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  61306. */
  61307. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  61308. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  61309. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61310. if (isCube === void 0) { isCube = false; }
  61311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61312. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  61313. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  61314. if (isMulti === void 0) { isMulti = false; }
  61315. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61316. _this.isCube = isCube;
  61317. /**
  61318. * Use this list to define the list of mesh you want to render.
  61319. */
  61320. _this.renderList = new Array();
  61321. _this.renderParticles = true;
  61322. _this.renderSprites = false;
  61323. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  61324. _this.ignoreCameraViewport = false;
  61325. // Events
  61326. /**
  61327. * An event triggered when the texture is unbind.
  61328. */
  61329. _this.onBeforeBindObservable = new BABYLON.Observable();
  61330. /**
  61331. * An event triggered when the texture is unbind.
  61332. */
  61333. _this.onAfterUnbindObservable = new BABYLON.Observable();
  61334. /**
  61335. * An event triggered before rendering the texture
  61336. */
  61337. _this.onBeforeRenderObservable = new BABYLON.Observable();
  61338. /**
  61339. * An event triggered after rendering the texture
  61340. */
  61341. _this.onAfterRenderObservable = new BABYLON.Observable();
  61342. /**
  61343. * An event triggered after the texture clear
  61344. */
  61345. _this.onClearObservable = new BABYLON.Observable();
  61346. _this._currentRefreshId = -1;
  61347. _this._refreshRate = 1;
  61348. _this._samples = 1;
  61349. /**
  61350. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  61351. * It must define where the camera used to render the texture is set
  61352. */
  61353. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61354. scene = _this.getScene();
  61355. if (!scene) {
  61356. return _this;
  61357. }
  61358. _this._engine = scene.getEngine();
  61359. _this.name = name;
  61360. _this.isRenderTarget = true;
  61361. _this._initialSizeParameter = size;
  61362. _this._processSizeParameter(size);
  61363. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  61364. });
  61365. _this._generateMipMaps = generateMipMaps ? true : false;
  61366. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  61367. // Rendering groups
  61368. _this._renderingManager = new BABYLON.RenderingManager(scene);
  61369. if (isMulti) {
  61370. return _this;
  61371. }
  61372. _this._renderTargetOptions = {
  61373. generateMipMaps: generateMipMaps,
  61374. type: type,
  61375. samplingMode: samplingMode,
  61376. generateDepthBuffer: generateDepthBuffer,
  61377. generateStencilBuffer: generateStencilBuffer
  61378. };
  61379. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  61380. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61381. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61382. }
  61383. if (isCube) {
  61384. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  61385. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  61386. _this._textureMatrix = BABYLON.Matrix.Identity();
  61387. }
  61388. else {
  61389. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  61390. }
  61391. return _this;
  61392. }
  61393. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  61394. get: function () {
  61395. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  61396. },
  61397. enumerable: true,
  61398. configurable: true
  61399. });
  61400. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  61401. get: function () {
  61402. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  61403. },
  61404. enumerable: true,
  61405. configurable: true
  61406. });
  61407. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  61408. get: function () {
  61409. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  61410. },
  61411. enumerable: true,
  61412. configurable: true
  61413. });
  61414. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  61415. set: function (callback) {
  61416. if (this._onAfterUnbindObserver) {
  61417. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  61418. }
  61419. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  61420. },
  61421. enumerable: true,
  61422. configurable: true
  61423. });
  61424. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  61425. set: function (callback) {
  61426. if (this._onBeforeRenderObserver) {
  61427. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61428. }
  61429. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61430. },
  61431. enumerable: true,
  61432. configurable: true
  61433. });
  61434. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  61435. set: function (callback) {
  61436. if (this._onAfterRenderObserver) {
  61437. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61438. }
  61439. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61440. },
  61441. enumerable: true,
  61442. configurable: true
  61443. });
  61444. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  61445. set: function (callback) {
  61446. if (this._onClearObserver) {
  61447. this.onClearObservable.remove(this._onClearObserver);
  61448. }
  61449. this._onClearObserver = this.onClearObservable.add(callback);
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  61455. get: function () {
  61456. return this._renderTargetOptions;
  61457. },
  61458. enumerable: true,
  61459. configurable: true
  61460. });
  61461. RenderTargetTexture.prototype._onRatioRescale = function () {
  61462. if (this._sizeRatio) {
  61463. this.resize(this._initialSizeParameter);
  61464. }
  61465. };
  61466. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  61467. get: function () {
  61468. return this._boundingBoxSize;
  61469. },
  61470. /**
  61471. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  61472. * When defined, the cubemap will switch to local mode
  61473. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61474. * @example https://www.babylonjs-playground.com/#RNASML
  61475. */
  61476. set: function (value) {
  61477. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61478. return;
  61479. }
  61480. this._boundingBoxSize = value;
  61481. var scene = this.getScene();
  61482. if (scene) {
  61483. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61484. }
  61485. },
  61486. enumerable: true,
  61487. configurable: true
  61488. });
  61489. /**
  61490. * Creates a depth stencil texture.
  61491. * This is only available in WebGL 2 or with the depth texture extension available.
  61492. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  61493. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  61494. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  61495. */
  61496. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  61497. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  61498. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  61499. if (generateStencil === void 0) { generateStencil = false; }
  61500. if (!this.getScene()) {
  61501. return;
  61502. }
  61503. var engine = this.getScene().getEngine();
  61504. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  61505. bilinearFiltering: bilinearFiltering,
  61506. comparisonFunction: comparisonFunction,
  61507. generateStencil: generateStencil,
  61508. isCube: this.isCube
  61509. });
  61510. engine.setFrameBufferDepthStencilTexture(this);
  61511. };
  61512. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  61513. if (size.ratio) {
  61514. this._sizeRatio = size.ratio;
  61515. this._size = {
  61516. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  61517. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  61518. };
  61519. }
  61520. else {
  61521. this._size = size;
  61522. }
  61523. };
  61524. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  61525. get: function () {
  61526. return this._samples;
  61527. },
  61528. set: function (value) {
  61529. if (this._samples === value) {
  61530. return;
  61531. }
  61532. var scene = this.getScene();
  61533. if (!scene) {
  61534. return;
  61535. }
  61536. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  61537. },
  61538. enumerable: true,
  61539. configurable: true
  61540. });
  61541. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  61542. this._currentRefreshId = -1;
  61543. };
  61544. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  61545. get: function () {
  61546. return this._refreshRate;
  61547. },
  61548. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61549. set: function (value) {
  61550. this._refreshRate = value;
  61551. this.resetRefreshCounter();
  61552. },
  61553. enumerable: true,
  61554. configurable: true
  61555. });
  61556. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  61557. if (!this._postProcessManager) {
  61558. var scene = this.getScene();
  61559. if (!scene) {
  61560. return;
  61561. }
  61562. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  61563. this._postProcesses = new Array();
  61564. }
  61565. this._postProcesses.push(postProcess);
  61566. this._postProcesses[0].autoClear = false;
  61567. };
  61568. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  61569. if (!this._postProcesses) {
  61570. return;
  61571. }
  61572. if (dispose) {
  61573. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  61574. var postProcess = _a[_i];
  61575. postProcess.dispose();
  61576. }
  61577. }
  61578. this._postProcesses = [];
  61579. };
  61580. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  61581. if (!this._postProcesses) {
  61582. return;
  61583. }
  61584. var index = this._postProcesses.indexOf(postProcess);
  61585. if (index === -1) {
  61586. return;
  61587. }
  61588. this._postProcesses.splice(index, 1);
  61589. if (this._postProcesses.length > 0) {
  61590. this._postProcesses[0].autoClear = false;
  61591. }
  61592. };
  61593. RenderTargetTexture.prototype._shouldRender = function () {
  61594. if (this._currentRefreshId === -1) {
  61595. this._currentRefreshId = 1;
  61596. return true;
  61597. }
  61598. if (this.refreshRate === this._currentRefreshId) {
  61599. this._currentRefreshId = 1;
  61600. return true;
  61601. }
  61602. this._currentRefreshId++;
  61603. return false;
  61604. };
  61605. RenderTargetTexture.prototype.getRenderSize = function () {
  61606. if (this._size.width) {
  61607. return this._size.width;
  61608. }
  61609. return this._size;
  61610. };
  61611. RenderTargetTexture.prototype.getRenderWidth = function () {
  61612. if (this._size.width) {
  61613. return this._size.width;
  61614. }
  61615. return this._size;
  61616. };
  61617. RenderTargetTexture.prototype.getRenderHeight = function () {
  61618. if (this._size.width) {
  61619. return this._size.height;
  61620. }
  61621. return this._size;
  61622. };
  61623. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  61624. get: function () {
  61625. return true;
  61626. },
  61627. enumerable: true,
  61628. configurable: true
  61629. });
  61630. RenderTargetTexture.prototype.scale = function (ratio) {
  61631. var newSize = this.getRenderSize() * ratio;
  61632. this.resize(newSize);
  61633. };
  61634. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  61635. if (this.isCube) {
  61636. return this._textureMatrix;
  61637. }
  61638. return _super.prototype.getReflectionTextureMatrix.call(this);
  61639. };
  61640. RenderTargetTexture.prototype.resize = function (size) {
  61641. this.releaseInternalTexture();
  61642. var scene = this.getScene();
  61643. if (!scene) {
  61644. return;
  61645. }
  61646. this._processSizeParameter(size);
  61647. if (this.isCube) {
  61648. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  61649. }
  61650. else {
  61651. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  61652. }
  61653. };
  61654. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  61655. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  61656. if (dumpForDebug === void 0) { dumpForDebug = false; }
  61657. var scene = this.getScene();
  61658. if (!scene) {
  61659. return;
  61660. }
  61661. var engine = scene.getEngine();
  61662. if (this.useCameraPostProcesses !== undefined) {
  61663. useCameraPostProcess = this.useCameraPostProcesses;
  61664. }
  61665. if (this._waitingRenderList) {
  61666. this.renderList = [];
  61667. for (var index = 0; index < this._waitingRenderList.length; index++) {
  61668. var id = this._waitingRenderList[index];
  61669. var mesh_1 = scene.getMeshByID(id);
  61670. if (mesh_1) {
  61671. this.renderList.push(mesh_1);
  61672. }
  61673. }
  61674. delete this._waitingRenderList;
  61675. }
  61676. // Is predicate defined?
  61677. if (this.renderListPredicate) {
  61678. if (this.renderList) {
  61679. this.renderList.splice(0); // Clear previous renderList
  61680. }
  61681. else {
  61682. this.renderList = [];
  61683. }
  61684. var scene = this.getScene();
  61685. if (!scene) {
  61686. return;
  61687. }
  61688. var sceneMeshes = scene.meshes;
  61689. for (var index = 0; index < sceneMeshes.length; index++) {
  61690. var mesh = sceneMeshes[index];
  61691. if (this.renderListPredicate(mesh)) {
  61692. this.renderList.push(mesh);
  61693. }
  61694. }
  61695. }
  61696. this.onBeforeBindObservable.notifyObservers(this);
  61697. // Set custom projection.
  61698. // Needs to be before binding to prevent changing the aspect ratio.
  61699. var camera;
  61700. if (this.activeCamera) {
  61701. camera = this.activeCamera;
  61702. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  61703. if (this.activeCamera !== scene.activeCamera) {
  61704. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  61705. }
  61706. }
  61707. else {
  61708. camera = scene.activeCamera;
  61709. if (camera) {
  61710. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  61711. }
  61712. }
  61713. // Prepare renderingManager
  61714. this._renderingManager.reset();
  61715. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  61716. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  61717. var sceneRenderId = scene.getRenderId();
  61718. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  61719. var mesh = currentRenderList[meshIndex];
  61720. if (mesh) {
  61721. if (!mesh.isReady(this.refreshRate === 0)) {
  61722. this.resetRefreshCounter();
  61723. continue;
  61724. }
  61725. mesh._preActivateForIntermediateRendering(sceneRenderId);
  61726. var isMasked = void 0;
  61727. if (!this.renderList && camera) {
  61728. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  61729. }
  61730. else {
  61731. isMasked = false;
  61732. }
  61733. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  61734. mesh._activate(sceneRenderId);
  61735. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  61736. var subMesh = mesh.subMeshes[subIndex];
  61737. scene._activeIndices.addCount(subMesh.indexCount, false);
  61738. this._renderingManager.dispatch(subMesh, mesh);
  61739. }
  61740. }
  61741. }
  61742. }
  61743. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  61744. var particleSystem = scene.particleSystems[particleIndex];
  61745. var emitter = particleSystem.emitter;
  61746. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  61747. continue;
  61748. }
  61749. if (currentRenderList.indexOf(emitter) >= 0) {
  61750. this._renderingManager.dispatchParticles(particleSystem);
  61751. }
  61752. }
  61753. if (this.isCube) {
  61754. for (var face = 0; face < 6; face++) {
  61755. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  61756. scene.incrementRenderId();
  61757. scene.resetCachedMaterial();
  61758. }
  61759. }
  61760. else {
  61761. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  61762. }
  61763. this.onAfterUnbindObservable.notifyObservers(this);
  61764. if (scene.activeCamera) {
  61765. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  61766. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  61767. }
  61768. engine.setViewport(scene.activeCamera.viewport);
  61769. }
  61770. scene.resetCachedMaterial();
  61771. };
  61772. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  61773. var minimum = 128;
  61774. var x = renderDimension * scale;
  61775. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  61776. // Ensure we don't exceed the render dimension (while staying POT)
  61777. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  61778. };
  61779. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  61780. var _this = this;
  61781. if (!this._texture) {
  61782. return;
  61783. }
  61784. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  61785. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  61786. });
  61787. };
  61788. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  61789. var scene = this.getScene();
  61790. if (!scene) {
  61791. return;
  61792. }
  61793. var engine = scene.getEngine();
  61794. if (!this._texture) {
  61795. return;
  61796. }
  61797. // Bind
  61798. if (this._postProcessManager) {
  61799. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  61800. }
  61801. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  61802. if (this._texture) {
  61803. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  61804. }
  61805. }
  61806. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  61807. // Clear
  61808. if (this.onClearObservable.hasObservers()) {
  61809. this.onClearObservable.notifyObservers(engine);
  61810. }
  61811. else {
  61812. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  61813. }
  61814. if (!this._doNotChangeAspectRatio) {
  61815. scene.updateTransformMatrix(true);
  61816. }
  61817. // Render
  61818. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  61819. if (this._postProcessManager) {
  61820. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  61821. }
  61822. else if (useCameraPostProcess) {
  61823. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  61824. }
  61825. if (!this._doNotChangeAspectRatio) {
  61826. scene.updateTransformMatrix(true);
  61827. }
  61828. // Dump ?
  61829. if (dumpForDebug) {
  61830. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  61831. }
  61832. // Unbind
  61833. if (!this.isCube || faceIndex === 5) {
  61834. if (this.isCube) {
  61835. if (faceIndex === 5) {
  61836. engine.generateMipMapsForCubemap(this._texture);
  61837. }
  61838. }
  61839. this.unbindFrameBuffer(engine, faceIndex);
  61840. }
  61841. else {
  61842. this.onAfterRenderObservable.notifyObservers(faceIndex);
  61843. }
  61844. };
  61845. /**
  61846. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  61847. * This allowed control for front to back rendering or reversly depending of the special needs.
  61848. *
  61849. * @param renderingGroupId The rendering group id corresponding to its index
  61850. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  61851. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  61852. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  61853. */
  61854. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  61855. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  61856. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  61857. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  61858. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  61859. };
  61860. /**
  61861. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  61862. *
  61863. * @param renderingGroupId The rendering group id corresponding to its index
  61864. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  61865. */
  61866. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  61867. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  61868. };
  61869. RenderTargetTexture.prototype.clone = function () {
  61870. var textureSize = this.getSize();
  61871. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  61872. // Base texture
  61873. newTexture.hasAlpha = this.hasAlpha;
  61874. newTexture.level = this.level;
  61875. // RenderTarget Texture
  61876. newTexture.coordinatesMode = this.coordinatesMode;
  61877. if (this.renderList) {
  61878. newTexture.renderList = this.renderList.slice(0);
  61879. }
  61880. return newTexture;
  61881. };
  61882. RenderTargetTexture.prototype.serialize = function () {
  61883. if (!this.name) {
  61884. return null;
  61885. }
  61886. var serializationObject = _super.prototype.serialize.call(this);
  61887. serializationObject.renderTargetSize = this.getRenderSize();
  61888. serializationObject.renderList = [];
  61889. if (this.renderList) {
  61890. for (var index = 0; index < this.renderList.length; index++) {
  61891. serializationObject.renderList.push(this.renderList[index].id);
  61892. }
  61893. }
  61894. return serializationObject;
  61895. };
  61896. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  61897. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  61898. var objBuffer = this.getInternalTexture();
  61899. var scene = this.getScene();
  61900. if (objBuffer && scene) {
  61901. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  61902. }
  61903. };
  61904. RenderTargetTexture.prototype.dispose = function () {
  61905. if (this._postProcessManager) {
  61906. this._postProcessManager.dispose();
  61907. this._postProcessManager = null;
  61908. }
  61909. this.clearPostProcesses(true);
  61910. if (this._resizeObserver) {
  61911. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  61912. this._resizeObserver = null;
  61913. }
  61914. this.renderList = null;
  61915. // Remove from custom render targets
  61916. var scene = this.getScene();
  61917. if (!scene) {
  61918. return;
  61919. }
  61920. var index = scene.customRenderTargets.indexOf(this);
  61921. if (index >= 0) {
  61922. scene.customRenderTargets.splice(index, 1);
  61923. }
  61924. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  61925. var camera = _a[_i];
  61926. index = camera.customRenderTargets.indexOf(this);
  61927. if (index >= 0) {
  61928. camera.customRenderTargets.splice(index, 1);
  61929. }
  61930. }
  61931. _super.prototype.dispose.call(this);
  61932. };
  61933. RenderTargetTexture.prototype._rebuild = function () {
  61934. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61935. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61936. }
  61937. if (this._postProcessManager) {
  61938. this._postProcessManager._rebuild();
  61939. }
  61940. };
  61941. /**
  61942. * Clear the info related to rendering groups preventing retention point in material dispose.
  61943. */
  61944. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  61945. if (this._renderingManager) {
  61946. this._renderingManager.freeRenderingGroups();
  61947. }
  61948. };
  61949. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  61950. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  61951. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  61952. return RenderTargetTexture;
  61953. }(BABYLON.Texture));
  61954. BABYLON.RenderTargetTexture = RenderTargetTexture;
  61955. })(BABYLON || (BABYLON = {}));
  61956. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  61957. "use strict";
  61958. var BABYLON;
  61959. (function (BABYLON) {
  61960. ;
  61961. var MultiRenderTarget = /** @class */ (function (_super) {
  61962. __extends(MultiRenderTarget, _super);
  61963. function MultiRenderTarget(name, size, count, scene, options) {
  61964. var _this = this;
  61965. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  61966. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  61967. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  61968. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  61969. _this._engine = scene.getEngine();
  61970. if (!_this.isSupported) {
  61971. _this.dispose();
  61972. return;
  61973. }
  61974. var types = [];
  61975. var samplingModes = [];
  61976. for (var i = 0; i < count; i++) {
  61977. if (options && options.types && options.types[i] !== undefined) {
  61978. types.push(options.types[i]);
  61979. }
  61980. else {
  61981. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61982. }
  61983. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  61984. samplingModes.push(options.samplingModes[i]);
  61985. }
  61986. else {
  61987. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61988. }
  61989. }
  61990. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  61991. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  61992. _this._size = size;
  61993. _this._multiRenderTargetOptions = {
  61994. samplingModes: samplingModes,
  61995. generateMipMaps: generateMipMaps,
  61996. generateDepthBuffer: generateDepthBuffer,
  61997. generateStencilBuffer: generateStencilBuffer,
  61998. generateDepthTexture: generateDepthTexture,
  61999. types: types,
  62000. textureCount: count
  62001. };
  62002. _this._createInternalTextures();
  62003. _this._createTextures();
  62004. return _this;
  62005. }
  62006. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62007. get: function () {
  62008. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62009. },
  62010. enumerable: true,
  62011. configurable: true
  62012. });
  62013. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62014. get: function () {
  62015. return this._textures;
  62016. },
  62017. enumerable: true,
  62018. configurable: true
  62019. });
  62020. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62021. get: function () {
  62022. return this._textures[this._textures.length - 1];
  62023. },
  62024. enumerable: true,
  62025. configurable: true
  62026. });
  62027. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62028. set: function (wrap) {
  62029. if (this._textures) {
  62030. for (var i = 0; i < this._textures.length; i++) {
  62031. this._textures[i].wrapU = wrap;
  62032. }
  62033. }
  62034. },
  62035. enumerable: true,
  62036. configurable: true
  62037. });
  62038. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62039. set: function (wrap) {
  62040. if (this._textures) {
  62041. for (var i = 0; i < this._textures.length; i++) {
  62042. this._textures[i].wrapV = wrap;
  62043. }
  62044. }
  62045. },
  62046. enumerable: true,
  62047. configurable: true
  62048. });
  62049. MultiRenderTarget.prototype._rebuild = function () {
  62050. this.releaseInternalTextures();
  62051. this._createInternalTextures();
  62052. for (var i = 0; i < this._internalTextures.length; i++) {
  62053. var texture = this._textures[i];
  62054. texture._texture = this._internalTextures[i];
  62055. }
  62056. // Keeps references to frame buffer and stencil/depth buffer
  62057. this._texture = this._internalTextures[0];
  62058. };
  62059. MultiRenderTarget.prototype._createInternalTextures = function () {
  62060. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62061. };
  62062. MultiRenderTarget.prototype._createTextures = function () {
  62063. this._textures = [];
  62064. for (var i = 0; i < this._internalTextures.length; i++) {
  62065. var texture = new BABYLON.Texture(null, this.getScene());
  62066. texture._texture = this._internalTextures[i];
  62067. this._textures.push(texture);
  62068. }
  62069. // Keeps references to frame buffer and stencil/depth buffer
  62070. this._texture = this._internalTextures[0];
  62071. };
  62072. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62073. get: function () {
  62074. return this._samples;
  62075. },
  62076. set: function (value) {
  62077. if (this._samples === value) {
  62078. return;
  62079. }
  62080. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62081. },
  62082. enumerable: true,
  62083. configurable: true
  62084. });
  62085. MultiRenderTarget.prototype.resize = function (size) {
  62086. this.releaseInternalTextures();
  62087. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62088. this._createInternalTextures();
  62089. };
  62090. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62091. var _this = this;
  62092. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62093. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62094. });
  62095. };
  62096. MultiRenderTarget.prototype.dispose = function () {
  62097. this.releaseInternalTextures();
  62098. _super.prototype.dispose.call(this);
  62099. };
  62100. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62101. if (!this._internalTextures) {
  62102. return;
  62103. }
  62104. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62105. if (this._internalTextures[i] !== undefined) {
  62106. this._internalTextures[i].dispose();
  62107. this._internalTextures.splice(i, 1);
  62108. }
  62109. }
  62110. };
  62111. return MultiRenderTarget;
  62112. }(BABYLON.RenderTargetTexture));
  62113. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62114. })(BABYLON || (BABYLON = {}));
  62115. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62116. "use strict";
  62117. var BABYLON;
  62118. (function (BABYLON) {
  62119. var MirrorTexture = /** @class */ (function (_super) {
  62120. __extends(MirrorTexture, _super);
  62121. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62122. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62124. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62125. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62126. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62127. _this._transformMatrix = BABYLON.Matrix.Zero();
  62128. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62129. _this._adaptiveBlurKernel = 0;
  62130. _this._blurKernelX = 0;
  62131. _this._blurKernelY = 0;
  62132. _this._blurRatio = 1.0;
  62133. _this.ignoreCameraViewport = true;
  62134. _this.onBeforeRenderObservable.add(function () {
  62135. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62136. _this._savedViewMatrix = scene.getViewMatrix();
  62137. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62138. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62139. scene.clipPlane = _this.mirrorPlane;
  62140. scene.getEngine().cullBackFaces = false;
  62141. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62142. });
  62143. _this.onAfterRenderObservable.add(function () {
  62144. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62145. scene.getEngine().cullBackFaces = true;
  62146. scene._mirroredCameraPosition = null;
  62147. delete scene.clipPlane;
  62148. });
  62149. return _this;
  62150. }
  62151. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62152. get: function () {
  62153. return this._blurRatio;
  62154. },
  62155. set: function (value) {
  62156. if (this._blurRatio === value) {
  62157. return;
  62158. }
  62159. this._blurRatio = value;
  62160. this._preparePostProcesses();
  62161. },
  62162. enumerable: true,
  62163. configurable: true
  62164. });
  62165. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62166. set: function (value) {
  62167. this._adaptiveBlurKernel = value;
  62168. this._autoComputeBlurKernel();
  62169. },
  62170. enumerable: true,
  62171. configurable: true
  62172. });
  62173. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62174. set: function (value) {
  62175. this.blurKernelX = value;
  62176. this.blurKernelY = value;
  62177. },
  62178. enumerable: true,
  62179. configurable: true
  62180. });
  62181. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62182. get: function () {
  62183. return this._blurKernelX;
  62184. },
  62185. set: function (value) {
  62186. if (this._blurKernelX === value) {
  62187. return;
  62188. }
  62189. this._blurKernelX = value;
  62190. this._preparePostProcesses();
  62191. },
  62192. enumerable: true,
  62193. configurable: true
  62194. });
  62195. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62196. get: function () {
  62197. return this._blurKernelY;
  62198. },
  62199. set: function (value) {
  62200. if (this._blurKernelY === value) {
  62201. return;
  62202. }
  62203. this._blurKernelY = value;
  62204. this._preparePostProcesses();
  62205. },
  62206. enumerable: true,
  62207. configurable: true
  62208. });
  62209. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62210. var engine = this.getScene().getEngine();
  62211. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62212. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62213. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62214. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62215. };
  62216. MirrorTexture.prototype._onRatioRescale = function () {
  62217. if (this._sizeRatio) {
  62218. this.resize(this._initialSizeParameter);
  62219. if (!this._adaptiveBlurKernel) {
  62220. this._preparePostProcesses();
  62221. }
  62222. }
  62223. if (this._adaptiveBlurKernel) {
  62224. this._autoComputeBlurKernel();
  62225. }
  62226. };
  62227. MirrorTexture.prototype._preparePostProcesses = function () {
  62228. this.clearPostProcesses(true);
  62229. if (this._blurKernelX && this._blurKernelY) {
  62230. var engine = this.getScene().getEngine();
  62231. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62232. 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);
  62233. this._blurX.autoClear = false;
  62234. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62235. this._blurX.inputTexture = this._texture;
  62236. }
  62237. else {
  62238. this._blurX.alwaysForcePOT = true;
  62239. }
  62240. 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);
  62241. this._blurY.autoClear = false;
  62242. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62243. this.addPostProcess(this._blurX);
  62244. this.addPostProcess(this._blurY);
  62245. }
  62246. else {
  62247. if (this._blurY) {
  62248. this.removePostProcess(this._blurY);
  62249. this._blurY.dispose();
  62250. this._blurY = null;
  62251. }
  62252. if (this._blurX) {
  62253. this.removePostProcess(this._blurX);
  62254. this._blurX.dispose();
  62255. this._blurX = null;
  62256. }
  62257. }
  62258. };
  62259. MirrorTexture.prototype.clone = function () {
  62260. var scene = this.getScene();
  62261. if (!scene) {
  62262. return this;
  62263. }
  62264. var textureSize = this.getSize();
  62265. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62266. // Base texture
  62267. newTexture.hasAlpha = this.hasAlpha;
  62268. newTexture.level = this.level;
  62269. // Mirror Texture
  62270. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62271. if (this.renderList) {
  62272. newTexture.renderList = this.renderList.slice(0);
  62273. }
  62274. return newTexture;
  62275. };
  62276. MirrorTexture.prototype.serialize = function () {
  62277. if (!this.name) {
  62278. return null;
  62279. }
  62280. var serializationObject = _super.prototype.serialize.call(this);
  62281. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  62282. return serializationObject;
  62283. };
  62284. return MirrorTexture;
  62285. }(BABYLON.RenderTargetTexture));
  62286. BABYLON.MirrorTexture = MirrorTexture;
  62287. })(BABYLON || (BABYLON = {}));
  62288. //# sourceMappingURL=babylon.mirrorTexture.js.map
  62289. "use strict";
  62290. var BABYLON;
  62291. (function (BABYLON) {
  62292. /**
  62293. * Creates a refraction texture used by refraction channel of the standard material.
  62294. * @param name the texture name
  62295. * @param size size of the underlying texture
  62296. * @param scene root scene
  62297. */
  62298. var RefractionTexture = /** @class */ (function (_super) {
  62299. __extends(RefractionTexture, _super);
  62300. function RefractionTexture(name, size, scene, generateMipMaps) {
  62301. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  62302. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  62303. _this.depth = 2.0;
  62304. _this.onBeforeRenderObservable.add(function () {
  62305. scene.clipPlane = _this.refractionPlane;
  62306. });
  62307. _this.onAfterRenderObservable.add(function () {
  62308. delete scene.clipPlane;
  62309. });
  62310. return _this;
  62311. }
  62312. RefractionTexture.prototype.clone = function () {
  62313. var scene = this.getScene();
  62314. if (!scene) {
  62315. return this;
  62316. }
  62317. var textureSize = this.getSize();
  62318. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  62319. // Base texture
  62320. newTexture.hasAlpha = this.hasAlpha;
  62321. newTexture.level = this.level;
  62322. // Refraction Texture
  62323. newTexture.refractionPlane = this.refractionPlane.clone();
  62324. if (this.renderList) {
  62325. newTexture.renderList = this.renderList.slice(0);
  62326. }
  62327. newTexture.depth = this.depth;
  62328. return newTexture;
  62329. };
  62330. RefractionTexture.prototype.serialize = function () {
  62331. if (!this.name) {
  62332. return null;
  62333. }
  62334. var serializationObject = _super.prototype.serialize.call(this);
  62335. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  62336. serializationObject.depth = this.depth;
  62337. return serializationObject;
  62338. };
  62339. return RefractionTexture;
  62340. }(BABYLON.RenderTargetTexture));
  62341. BABYLON.RefractionTexture = RefractionTexture;
  62342. })(BABYLON || (BABYLON = {}));
  62343. //# sourceMappingURL=babylon.refractionTexture.js.map
  62344. "use strict";
  62345. var BABYLON;
  62346. (function (BABYLON) {
  62347. /**
  62348. * A class extending {BABYLON.Texture} allowing drawing on a texture
  62349. * @see http://doc.babylonjs.com/how_to/dynamictexture
  62350. */
  62351. var DynamicTexture = /** @class */ (function (_super) {
  62352. __extends(DynamicTexture, _super);
  62353. /**
  62354. * Creates a {BABYLON.DynamicTexture}
  62355. * @param name defines the name of the texture
  62356. * @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
  62357. * @param scene defines the scene where you want the texture
  62358. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  62359. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  62360. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  62361. */
  62362. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  62363. if (scene === void 0) { scene = null; }
  62364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62365. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62366. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  62367. _this.name = name;
  62368. _this._engine = _this.getScene().getEngine();
  62369. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62370. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62371. _this._generateMipMaps = generateMipMaps;
  62372. if (options.getContext) {
  62373. _this._canvas = options;
  62374. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62375. }
  62376. else {
  62377. _this._canvas = document.createElement("canvas");
  62378. if (options.width) {
  62379. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62380. }
  62381. else {
  62382. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  62383. }
  62384. }
  62385. var textureSize = _this.getSize();
  62386. _this._canvas.width = textureSize.width;
  62387. _this._canvas.height = textureSize.height;
  62388. _this._context = _this._canvas.getContext("2d");
  62389. return _this;
  62390. }
  62391. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  62392. /**
  62393. * Gets the current state of canRescale
  62394. */
  62395. get: function () {
  62396. return true;
  62397. },
  62398. enumerable: true,
  62399. configurable: true
  62400. });
  62401. DynamicTexture.prototype._recreate = function (textureSize) {
  62402. this._canvas.width = textureSize.width;
  62403. this._canvas.height = textureSize.height;
  62404. this.releaseInternalTexture();
  62405. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  62406. };
  62407. /**
  62408. * Scales the texture
  62409. * @param ratio the scale factor to apply to both width and height
  62410. */
  62411. DynamicTexture.prototype.scale = function (ratio) {
  62412. var textureSize = this.getSize();
  62413. textureSize.width *= ratio;
  62414. textureSize.height *= ratio;
  62415. this._recreate(textureSize);
  62416. };
  62417. /**
  62418. * Resizes the texture
  62419. * @param width the new width
  62420. * @param height the new height
  62421. */
  62422. DynamicTexture.prototype.scaleTo = function (width, height) {
  62423. var textureSize = this.getSize();
  62424. textureSize.width = width;
  62425. textureSize.height = height;
  62426. this._recreate(textureSize);
  62427. };
  62428. /**
  62429. * Gets the context of the canvas used by the texture
  62430. * @returns the canvas context of the dynamic texture
  62431. */
  62432. DynamicTexture.prototype.getContext = function () {
  62433. return this._context;
  62434. };
  62435. /**
  62436. * Clears the texture
  62437. */
  62438. DynamicTexture.prototype.clear = function () {
  62439. var size = this.getSize();
  62440. this._context.fillRect(0, 0, size.width, size.height);
  62441. };
  62442. /**
  62443. * Updates the texture
  62444. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62445. */
  62446. DynamicTexture.prototype.update = function (invertY) {
  62447. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  62448. };
  62449. /**
  62450. * Draws text onto the texture
  62451. * @param text defines the text to be drawn
  62452. * @param x defines the placement of the text from the left
  62453. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  62454. * @param font defines the font to be used with font-style, font-size, font-name
  62455. * @param color defines the color used for the text
  62456. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  62457. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62458. * @param update defines whether texture is immediately update (default is true)
  62459. */
  62460. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  62461. if (update === void 0) { update = true; }
  62462. var size = this.getSize();
  62463. if (clearColor) {
  62464. this._context.fillStyle = clearColor;
  62465. this._context.fillRect(0, 0, size.width, size.height);
  62466. }
  62467. this._context.font = font;
  62468. if (x === null || x === undefined) {
  62469. var textSize = this._context.measureText(text);
  62470. x = (size.width - textSize.width) / 2;
  62471. }
  62472. if (y === null || y === undefined) {
  62473. var fontSize = parseInt((font.replace(/\D/g, '')));
  62474. ;
  62475. y = (size.height / 2) + (fontSize / 3.65);
  62476. }
  62477. this._context.fillStyle = color;
  62478. this._context.fillText(text, x, y);
  62479. if (update) {
  62480. this.update(invertY);
  62481. }
  62482. };
  62483. /**
  62484. * Clones the texture
  62485. * @returns the clone of the texture.
  62486. */
  62487. DynamicTexture.prototype.clone = function () {
  62488. var scene = this.getScene();
  62489. if (!scene) {
  62490. return this;
  62491. }
  62492. var textureSize = this.getSize();
  62493. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  62494. // Base texture
  62495. newTexture.hasAlpha = this.hasAlpha;
  62496. newTexture.level = this.level;
  62497. // Dynamic Texture
  62498. newTexture.wrapU = this.wrapU;
  62499. newTexture.wrapV = this.wrapV;
  62500. return newTexture;
  62501. };
  62502. /** @ignore */
  62503. DynamicTexture.prototype._rebuild = function () {
  62504. this.update();
  62505. };
  62506. return DynamicTexture;
  62507. }(BABYLON.Texture));
  62508. BABYLON.DynamicTexture = DynamicTexture;
  62509. })(BABYLON || (BABYLON = {}));
  62510. //# sourceMappingURL=babylon.dynamicTexture.js.map
  62511. "use strict";
  62512. var BABYLON;
  62513. (function (BABYLON) {
  62514. var VideoTexture = /** @class */ (function (_super) {
  62515. __extends(VideoTexture, _super);
  62516. /**
  62517. * Creates a video texture.
  62518. * Sample : https://doc.babylonjs.com/how_to/video_texture
  62519. * @param {string | null} name optional name, will detect from video source, if not defined
  62520. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  62521. * @param {BABYLON.Scene} scene is obviously the current scene.
  62522. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  62523. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  62524. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  62525. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  62526. */
  62527. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  62528. if (generateMipMaps === void 0) { generateMipMaps = false; }
  62529. if (invertY === void 0) { invertY = false; }
  62530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62531. if (settings === void 0) { settings = {
  62532. autoPlay: true,
  62533. loop: true,
  62534. autoUpdateTexture: true,
  62535. }; }
  62536. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62537. _this._createInternalTexture = function () {
  62538. if (_this._texture != null) {
  62539. return;
  62540. }
  62541. if (!_this._engine.needPOTTextures ||
  62542. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  62543. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62544. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62545. }
  62546. else {
  62547. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62548. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62549. _this._generateMipMaps = false;
  62550. }
  62551. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  62552. _this._texture.isReady = true;
  62553. _this._updateInternalTexture();
  62554. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  62555. _this.onLoadObservable.notifyObservers(_this);
  62556. }
  62557. };
  62558. _this.reset = function () {
  62559. if (_this._texture == null) {
  62560. return;
  62561. }
  62562. _this._texture.dispose();
  62563. _this._texture = null;
  62564. };
  62565. _this._updateInternalTexture = function (e) {
  62566. if (_this._texture == null || !_this._texture.isReady) {
  62567. return;
  62568. }
  62569. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  62570. return;
  62571. }
  62572. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  62573. };
  62574. _this._engine = _this.getScene().getEngine();
  62575. _this._generateMipMaps = generateMipMaps;
  62576. _this._samplingMode = samplingMode;
  62577. _this.autoUpdateTexture = settings.autoUpdateTexture;
  62578. _this.name = name || _this._getName(src);
  62579. _this.video = _this._getVideo(src);
  62580. if (settings.autoPlay !== undefined) {
  62581. _this.video.autoplay = settings.autoPlay;
  62582. }
  62583. if (settings.loop !== undefined) {
  62584. _this.video.loop = settings.loop;
  62585. }
  62586. _this.video.addEventListener("canplay", _this._createInternalTexture);
  62587. _this.video.addEventListener("paused", _this._updateInternalTexture);
  62588. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  62589. _this.video.addEventListener("emptied", _this.reset);
  62590. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  62591. _this._createInternalTexture();
  62592. }
  62593. return _this;
  62594. }
  62595. VideoTexture.prototype._getName = function (src) {
  62596. if (src instanceof HTMLVideoElement) {
  62597. return src.currentSrc;
  62598. }
  62599. if (typeof src === "object") {
  62600. return src.toString();
  62601. }
  62602. return src;
  62603. };
  62604. ;
  62605. VideoTexture.prototype._getVideo = function (src) {
  62606. if (src instanceof HTMLVideoElement) {
  62607. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  62608. return src;
  62609. }
  62610. var video = document.createElement("video");
  62611. if (typeof src === "string") {
  62612. BABYLON.Tools.SetCorsBehavior(src, video);
  62613. video.src = src;
  62614. }
  62615. else {
  62616. BABYLON.Tools.SetCorsBehavior(src[0], video);
  62617. src.forEach(function (url) {
  62618. var source = document.createElement("source");
  62619. source.src = url;
  62620. video.appendChild(source);
  62621. });
  62622. }
  62623. return video;
  62624. };
  62625. ;
  62626. /**
  62627. * Internal method to initiate `update`.
  62628. */
  62629. VideoTexture.prototype._rebuild = function () {
  62630. this.update();
  62631. };
  62632. /**
  62633. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  62634. */
  62635. VideoTexture.prototype.update = function () {
  62636. if (!this.autoUpdateTexture) {
  62637. // Expecting user to call `updateTexture` manually
  62638. return;
  62639. }
  62640. this.updateTexture(true);
  62641. };
  62642. /**
  62643. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  62644. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  62645. */
  62646. VideoTexture.prototype.updateTexture = function (isVisible) {
  62647. if (!isVisible) {
  62648. return;
  62649. }
  62650. if (this.video.paused) {
  62651. return;
  62652. }
  62653. this._updateInternalTexture();
  62654. };
  62655. /**
  62656. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  62657. * @param url New url.
  62658. */
  62659. VideoTexture.prototype.updateURL = function (url) {
  62660. this.video.src = url;
  62661. };
  62662. VideoTexture.prototype.dispose = function () {
  62663. _super.prototype.dispose.call(this);
  62664. this.video.removeEventListener("canplay", this._createInternalTexture);
  62665. this.video.removeEventListener("paused", this._updateInternalTexture);
  62666. this.video.removeEventListener("seeked", this._updateInternalTexture);
  62667. this.video.removeEventListener("emptied", this.reset);
  62668. this.video.pause();
  62669. };
  62670. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  62671. var video = document.createElement("video");
  62672. var constraintsDeviceId;
  62673. if (constraints && constraints.deviceId) {
  62674. constraintsDeviceId = {
  62675. exact: constraints.deviceId,
  62676. };
  62677. }
  62678. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  62679. if (navigator.mediaDevices) {
  62680. navigator.mediaDevices.getUserMedia({ video: constraints })
  62681. .then(function (stream) {
  62682. if (video.mozSrcObject !== undefined) {
  62683. // hack for Firefox < 19
  62684. video.mozSrcObject = stream;
  62685. }
  62686. else {
  62687. video.srcObject = stream;
  62688. }
  62689. var onPlaying = function () {
  62690. if (onReady) {
  62691. onReady(new VideoTexture("video", video, scene, true, true));
  62692. }
  62693. video.removeEventListener("playing", onPlaying);
  62694. };
  62695. video.addEventListener("playing", onPlaying);
  62696. video.play();
  62697. })
  62698. .catch(function (err) {
  62699. BABYLON.Tools.Error(err.name);
  62700. });
  62701. }
  62702. else {
  62703. navigator.getUserMedia =
  62704. navigator.getUserMedia ||
  62705. navigator.webkitGetUserMedia ||
  62706. navigator.mozGetUserMedia ||
  62707. navigator.msGetUserMedia;
  62708. if (navigator.getUserMedia) {
  62709. navigator.getUserMedia({
  62710. video: {
  62711. deviceId: constraintsDeviceId,
  62712. width: {
  62713. min: (constraints && constraints.minWidth) || 256,
  62714. max: (constraints && constraints.maxWidth) || 640,
  62715. },
  62716. height: {
  62717. min: (constraints && constraints.minHeight) || 256,
  62718. max: (constraints && constraints.maxHeight) || 480,
  62719. },
  62720. },
  62721. }, function (stream) {
  62722. if (video.mozSrcObject !== undefined) {
  62723. // hack for Firefox < 19
  62724. video.mozSrcObject = stream;
  62725. }
  62726. else {
  62727. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  62728. }
  62729. video.play();
  62730. if (onReady) {
  62731. onReady(new VideoTexture("video", video, scene, true, true));
  62732. }
  62733. }, function (e) {
  62734. BABYLON.Tools.Error(e.name);
  62735. });
  62736. }
  62737. }
  62738. };
  62739. return VideoTexture;
  62740. }(BABYLON.Texture));
  62741. BABYLON.VideoTexture = VideoTexture;
  62742. })(BABYLON || (BABYLON = {}));
  62743. //# sourceMappingURL=babylon.videoTexture.js.map
  62744. "use strict";
  62745. var BABYLON;
  62746. (function (BABYLON) {
  62747. var RawTexture = /** @class */ (function (_super) {
  62748. __extends(RawTexture, _super);
  62749. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  62750. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62751. if (invertY === void 0) { invertY = false; }
  62752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62753. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62754. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62755. _this.format = format;
  62756. _this._engine = scene.getEngine();
  62757. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  62758. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62759. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62760. return _this;
  62761. }
  62762. RawTexture.prototype.update = function (data) {
  62763. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  62764. };
  62765. // Statics
  62766. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62767. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62768. if (invertY === void 0) { invertY = false; }
  62769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62770. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  62771. };
  62772. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62773. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62774. if (invertY === void 0) { invertY = false; }
  62775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62776. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  62777. };
  62778. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62779. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62780. if (invertY === void 0) { invertY = false; }
  62781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62782. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  62783. };
  62784. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  62785. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62786. if (invertY === void 0) { invertY = false; }
  62787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62788. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62789. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  62790. };
  62791. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  62792. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62793. if (invertY === void 0) { invertY = false; }
  62794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62795. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62796. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  62797. };
  62798. return RawTexture;
  62799. }(BABYLON.Texture));
  62800. BABYLON.RawTexture = RawTexture;
  62801. })(BABYLON || (BABYLON = {}));
  62802. //# sourceMappingURL=babylon.rawTexture.js.map
  62803. "use strict";
  62804. var BABYLON;
  62805. (function (BABYLON) {
  62806. /**
  62807. * PostProcess can be used to apply a shader to a texture after it has been rendered
  62808. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  62809. */
  62810. var PostProcess = /** @class */ (function () {
  62811. /**
  62812. * Creates a new instance PostProcess
  62813. * @param name The name of the PostProcess.
  62814. * @param fragmentUrl The url of the fragment shader to be used.
  62815. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  62816. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  62817. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  62818. * @param camera The camera to apply the render pass to.
  62819. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  62820. * @param engine The engine which the post process will be applied. (default: current engine)
  62821. * @param reusable If the post process can be reused on the same frame. (default: false)
  62822. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  62823. * @param textureType Type of textures used when performing the post process. (default: 0)
  62824. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  62825. * @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
  62826. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  62827. */
  62828. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  62829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  62830. if (defines === void 0) { defines = null; }
  62831. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62832. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  62833. if (blockCompilation === void 0) { blockCompilation = false; }
  62834. this.name = name;
  62835. /**
  62836. * Width of the texture to apply the post process on
  62837. */
  62838. this.width = -1;
  62839. /**
  62840. * Height of the texture to apply the post process on
  62841. */
  62842. this.height = -1;
  62843. /**
  62844. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  62845. */
  62846. this._outputTexture = null;
  62847. /**
  62848. * If the buffer needs to be cleared before applying the post process. (default: true)
  62849. * Should be set to false if shader will overwrite all previous pixels.
  62850. */
  62851. this.autoClear = true;
  62852. /**
  62853. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  62854. */
  62855. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  62856. /**
  62857. * Animations to be used for the post processing
  62858. */
  62859. this.animations = new Array();
  62860. /**
  62861. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  62862. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  62863. */
  62864. this.enablePixelPerfectMode = false;
  62865. /**
  62866. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  62867. */
  62868. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  62869. /**
  62870. * Force textures to be a power of two (default: false)
  62871. */
  62872. this.alwaysForcePOT = false;
  62873. /**
  62874. * Number of sample textures (default: 1)
  62875. */
  62876. this.samples = 1;
  62877. /**
  62878. * Modify the scale of the post process to be the same as the viewport (default: false)
  62879. */
  62880. this.adaptScaleToCurrentViewport = false;
  62881. this._reusable = false;
  62882. /**
  62883. * Smart array of input and output textures for the post process.
  62884. */
  62885. this._textures = new BABYLON.SmartArray(2);
  62886. /**
  62887. * The index in _textures that corresponds to the output texture.
  62888. */
  62889. this._currentRenderTextureInd = 0;
  62890. this._scaleRatio = new BABYLON.Vector2(1, 1);
  62891. this._texelSize = BABYLON.Vector2.Zero();
  62892. // Events
  62893. /**
  62894. * An event triggered when the postprocess is activated.
  62895. */
  62896. this.onActivateObservable = new BABYLON.Observable();
  62897. /**
  62898. * An event triggered when the postprocess changes its size.
  62899. */
  62900. this.onSizeChangedObservable = new BABYLON.Observable();
  62901. /**
  62902. * An event triggered when the postprocess applies its effect.
  62903. */
  62904. this.onApplyObservable = new BABYLON.Observable();
  62905. /**
  62906. * An event triggered before rendering the postprocess
  62907. */
  62908. this.onBeforeRenderObservable = new BABYLON.Observable();
  62909. /**
  62910. * An event triggered after rendering the postprocess
  62911. */
  62912. this.onAfterRenderObservable = new BABYLON.Observable();
  62913. if (camera != null) {
  62914. this._camera = camera;
  62915. this._scene = camera.getScene();
  62916. camera.attachPostProcess(this);
  62917. this._engine = this._scene.getEngine();
  62918. this._scene.postProcesses.push(this);
  62919. }
  62920. else if (engine) {
  62921. this._engine = engine;
  62922. this._engine.postProcesses.push(this);
  62923. }
  62924. this._options = options;
  62925. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  62926. this._reusable = reusable || false;
  62927. this._textureType = textureType;
  62928. this._samplers = samplers || [];
  62929. this._samplers.push("textureSampler");
  62930. this._fragmentUrl = fragmentUrl;
  62931. this._vertexUrl = vertexUrl;
  62932. this._parameters = parameters || [];
  62933. this._parameters.push("scale");
  62934. this._indexParameters = indexParameters;
  62935. if (!blockCompilation) {
  62936. this.updateEffect(defines);
  62937. }
  62938. }
  62939. Object.defineProperty(PostProcess.prototype, "onActivate", {
  62940. /**
  62941. * A function that is added to the onActivateObservable
  62942. */
  62943. set: function (callback) {
  62944. if (this._onActivateObserver) {
  62945. this.onActivateObservable.remove(this._onActivateObserver);
  62946. }
  62947. if (callback) {
  62948. this._onActivateObserver = this.onActivateObservable.add(callback);
  62949. }
  62950. },
  62951. enumerable: true,
  62952. configurable: true
  62953. });
  62954. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  62955. /**
  62956. * A function that is added to the onSizeChangedObservable
  62957. */
  62958. set: function (callback) {
  62959. if (this._onSizeChangedObserver) {
  62960. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  62961. }
  62962. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  62963. },
  62964. enumerable: true,
  62965. configurable: true
  62966. });
  62967. Object.defineProperty(PostProcess.prototype, "onApply", {
  62968. /**
  62969. * A function that is added to the onApplyObservable
  62970. */
  62971. set: function (callback) {
  62972. if (this._onApplyObserver) {
  62973. this.onApplyObservable.remove(this._onApplyObserver);
  62974. }
  62975. this._onApplyObserver = this.onApplyObservable.add(callback);
  62976. },
  62977. enumerable: true,
  62978. configurable: true
  62979. });
  62980. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  62981. /**
  62982. * A function that is added to the onBeforeRenderObservable
  62983. */
  62984. set: function (callback) {
  62985. if (this._onBeforeRenderObserver) {
  62986. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62987. }
  62988. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62989. },
  62990. enumerable: true,
  62991. configurable: true
  62992. });
  62993. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  62994. /**
  62995. * A function that is added to the onAfterRenderObservable
  62996. */
  62997. set: function (callback) {
  62998. if (this._onAfterRenderObserver) {
  62999. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63000. }
  63001. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63002. },
  63003. enumerable: true,
  63004. configurable: true
  63005. });
  63006. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63007. /**
  63008. * 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
  63009. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63010. */
  63011. get: function () {
  63012. return this._textures.data[this._currentRenderTextureInd];
  63013. },
  63014. set: function (value) {
  63015. this._forcedOutputTexture = value;
  63016. },
  63017. enumerable: true,
  63018. configurable: true
  63019. });
  63020. /**
  63021. * Gets the camera which post process is applied to.
  63022. * @returns The camera the post process is applied to.
  63023. */
  63024. PostProcess.prototype.getCamera = function () {
  63025. return this._camera;
  63026. };
  63027. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63028. /**
  63029. * Gets the texel size of the postprocess.
  63030. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63031. */
  63032. get: function () {
  63033. if (this._shareOutputWithPostProcess) {
  63034. return this._shareOutputWithPostProcess.texelSize;
  63035. }
  63036. if (this._forcedOutputTexture) {
  63037. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63038. }
  63039. return this._texelSize;
  63040. },
  63041. enumerable: true,
  63042. configurable: true
  63043. });
  63044. /**
  63045. * Gets the engine which this post process belongs to.
  63046. * @returns The engine the post process was enabled with.
  63047. */
  63048. PostProcess.prototype.getEngine = function () {
  63049. return this._engine;
  63050. };
  63051. /**
  63052. * The effect that is created when initializing the post process.
  63053. * @returns The created effect corrisponding the the postprocess.
  63054. */
  63055. PostProcess.prototype.getEffect = function () {
  63056. return this._effect;
  63057. };
  63058. /**
  63059. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  63060. * @param postProcess The post process to share the output with.
  63061. * @returns This post process.
  63062. */
  63063. PostProcess.prototype.shareOutputWith = function (postProcess) {
  63064. this._disposeTextures();
  63065. this._shareOutputWithPostProcess = postProcess;
  63066. return this;
  63067. };
  63068. /**
  63069. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  63070. * This should be called if the post process that shares output with this post process is disabled/disposed.
  63071. */
  63072. PostProcess.prototype.useOwnOutput = function () {
  63073. if (this._textures.length == 0) {
  63074. this._textures = new BABYLON.SmartArray(2);
  63075. }
  63076. this._shareOutputWithPostProcess = null;
  63077. };
  63078. /**
  63079. * Updates the effect with the current post process compile time values and recompiles the shader.
  63080. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63081. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63082. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63083. * @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
  63084. * @param onCompiled Called when the shader has been compiled.
  63085. * @param onError Called if there is an error when compiling a shader.
  63086. */
  63087. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63088. if (defines === void 0) { defines = null; }
  63089. if (uniforms === void 0) { uniforms = null; }
  63090. if (samplers === void 0) { samplers = null; }
  63091. 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);
  63092. };
  63093. /**
  63094. * The post process is reusable if it can be used multiple times within one frame.
  63095. * @returns If the post process is reusable
  63096. */
  63097. PostProcess.prototype.isReusable = function () {
  63098. return this._reusable;
  63099. };
  63100. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  63101. PostProcess.prototype.markTextureDirty = function () {
  63102. this.width = -1;
  63103. };
  63104. /**
  63105. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  63106. * 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.
  63107. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63108. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63109. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63110. * @returns The target texture that was bound to be written to.
  63111. */
  63112. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63113. var _this = this;
  63114. if (sourceTexture === void 0) { sourceTexture = null; }
  63115. camera = camera || this._camera;
  63116. var scene = camera.getScene();
  63117. var engine = scene.getEngine();
  63118. var maxSize = engine.getCaps().maxTextureSize;
  63119. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63120. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63121. // 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
  63122. var webVRCamera = camera.parent;
  63123. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63124. requiredWidth /= 2;
  63125. }
  63126. var desiredWidth = (this._options.width || requiredWidth);
  63127. var desiredHeight = this._options.height || requiredHeight;
  63128. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63129. if (this.adaptScaleToCurrentViewport) {
  63130. var currentViewport = engine.currentViewport;
  63131. if (currentViewport) {
  63132. desiredWidth *= currentViewport.width;
  63133. desiredHeight *= currentViewport.height;
  63134. }
  63135. }
  63136. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63137. if (!this._options.width) {
  63138. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63139. }
  63140. if (!this._options.height) {
  63141. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63142. }
  63143. }
  63144. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63145. if (this._textures.length > 0) {
  63146. for (var i = 0; i < this._textures.length; i++) {
  63147. this._engine._releaseTexture(this._textures.data[i]);
  63148. }
  63149. this._textures.reset();
  63150. }
  63151. this.width = desiredWidth;
  63152. this.height = desiredHeight;
  63153. var textureSize = { width: this.width, height: this.height };
  63154. var textureOptions = {
  63155. generateMipMaps: false,
  63156. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63157. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63158. samplingMode: this.renderTargetSamplingMode,
  63159. type: this._textureType
  63160. };
  63161. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63162. if (this._reusable) {
  63163. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63164. }
  63165. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63166. this.onSizeChangedObservable.notifyObservers(this);
  63167. }
  63168. this._textures.forEach(function (texture) {
  63169. if (texture.samples !== _this.samples) {
  63170. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63171. }
  63172. });
  63173. }
  63174. var target;
  63175. if (this._shareOutputWithPostProcess) {
  63176. target = this._shareOutputWithPostProcess.inputTexture;
  63177. }
  63178. else if (this._forcedOutputTexture) {
  63179. target = this._forcedOutputTexture;
  63180. this.width = this._forcedOutputTexture.width;
  63181. this.height = this._forcedOutputTexture.height;
  63182. }
  63183. else {
  63184. target = this.inputTexture;
  63185. }
  63186. // Bind the input of this post process to be used as the output of the previous post process.
  63187. if (this.enablePixelPerfectMode) {
  63188. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63189. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63190. }
  63191. else {
  63192. this._scaleRatio.copyFromFloats(1, 1);
  63193. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63194. }
  63195. this.onActivateObservable.notifyObservers(camera);
  63196. // Clear
  63197. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63198. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63199. }
  63200. if (this._reusable) {
  63201. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63202. }
  63203. return target;
  63204. };
  63205. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63206. /**
  63207. * If the post process is supported.
  63208. */
  63209. get: function () {
  63210. return this._effect.isSupported;
  63211. },
  63212. enumerable: true,
  63213. configurable: true
  63214. });
  63215. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63216. /**
  63217. * The aspect ratio of the output texture.
  63218. */
  63219. get: function () {
  63220. if (this._shareOutputWithPostProcess) {
  63221. return this._shareOutputWithPostProcess.aspectRatio;
  63222. }
  63223. if (this._forcedOutputTexture) {
  63224. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63225. }
  63226. return this.width / this.height;
  63227. },
  63228. enumerable: true,
  63229. configurable: true
  63230. });
  63231. /**
  63232. * Get a value indicating if the post-process is ready to be used
  63233. * @returns true if the post-process is ready (shader is compiled)
  63234. */
  63235. PostProcess.prototype.isReady = function () {
  63236. return this._effect && this._effect.isReady();
  63237. };
  63238. /**
  63239. * Binds all textures and uniforms to the shader, this will be run on every pass.
  63240. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  63241. */
  63242. PostProcess.prototype.apply = function () {
  63243. // Check
  63244. if (!this._effect || !this._effect.isReady())
  63245. return null;
  63246. // States
  63247. this._engine.enableEffect(this._effect);
  63248. this._engine.setState(false);
  63249. this._engine.setDepthBuffer(false);
  63250. this._engine.setDepthWrite(false);
  63251. // Alpha
  63252. this._engine.setAlphaMode(this.alphaMode);
  63253. if (this.alphaConstants) {
  63254. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  63255. }
  63256. // Bind the output texture of the preivous post process as the input to this post process.
  63257. var source;
  63258. if (this._shareOutputWithPostProcess) {
  63259. source = this._shareOutputWithPostProcess.inputTexture;
  63260. }
  63261. else if (this._forcedOutputTexture) {
  63262. source = this._forcedOutputTexture;
  63263. }
  63264. else {
  63265. source = this.inputTexture;
  63266. }
  63267. this._effect._bindTexture("textureSampler", source);
  63268. // Parameters
  63269. this._effect.setVector2("scale", this._scaleRatio);
  63270. this.onApplyObservable.notifyObservers(this._effect);
  63271. return this._effect;
  63272. };
  63273. PostProcess.prototype._disposeTextures = function () {
  63274. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  63275. return;
  63276. }
  63277. if (this._textures.length > 0) {
  63278. for (var i = 0; i < this._textures.length; i++) {
  63279. this._engine._releaseTexture(this._textures.data[i]);
  63280. }
  63281. }
  63282. this._textures.dispose();
  63283. };
  63284. /**
  63285. * Disposes the post process.
  63286. * @param camera The camera to dispose the post process on.
  63287. */
  63288. PostProcess.prototype.dispose = function (camera) {
  63289. camera = camera || this._camera;
  63290. this._disposeTextures();
  63291. if (this._scene) {
  63292. var index_1 = this._scene.postProcesses.indexOf(this);
  63293. if (index_1 !== -1) {
  63294. this._scene.postProcesses.splice(index_1, 1);
  63295. }
  63296. }
  63297. else {
  63298. var index_2 = this._engine.postProcesses.indexOf(this);
  63299. if (index_2 !== -1) {
  63300. this._engine.postProcesses.splice(index_2, 1);
  63301. }
  63302. }
  63303. if (!camera) {
  63304. return;
  63305. }
  63306. camera.detachPostProcess(this);
  63307. var index = camera._postProcesses.indexOf(this);
  63308. if (index === 0 && camera._postProcesses.length > 0) {
  63309. var firstPostProcess = this._camera._getFirstPostProcess();
  63310. if (firstPostProcess) {
  63311. firstPostProcess.markTextureDirty();
  63312. }
  63313. }
  63314. this.onActivateObservable.clear();
  63315. this.onAfterRenderObservable.clear();
  63316. this.onApplyObservable.clear();
  63317. this.onBeforeRenderObservable.clear();
  63318. this.onSizeChangedObservable.clear();
  63319. };
  63320. return PostProcess;
  63321. }());
  63322. BABYLON.PostProcess = PostProcess;
  63323. })(BABYLON || (BABYLON = {}));
  63324. //# sourceMappingURL=babylon.postProcess.js.map
  63325. "use strict";
  63326. var BABYLON;
  63327. (function (BABYLON) {
  63328. var PassPostProcess = /** @class */ (function (_super) {
  63329. __extends(PassPostProcess, _super);
  63330. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  63331. if (camera === void 0) { camera = null; }
  63332. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63333. if (blockCompilation === void 0) { blockCompilation = false; }
  63334. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  63335. }
  63336. return PassPostProcess;
  63337. }(BABYLON.PostProcess));
  63338. BABYLON.PassPostProcess = PassPostProcess;
  63339. })(BABYLON || (BABYLON = {}));
  63340. //# sourceMappingURL=babylon.passPostProcess.js.map
  63341. "use strict";
  63342. var __assign = (this && this.__assign) || Object.assign || function(t) {
  63343. for (var s, i = 1, n = arguments.length; i < n; i++) {
  63344. s = arguments[i];
  63345. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  63346. t[p] = s[p];
  63347. }
  63348. return t;
  63349. };
  63350. var BABYLON;
  63351. (function (BABYLON) {
  63352. /**
  63353. * Default implementation IShadowGenerator.
  63354. * This is the main object responsible of generating shadows in the framework.
  63355. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  63356. */
  63357. var ShadowGenerator = /** @class */ (function () {
  63358. /**
  63359. * Creates a ShadowGenerator object.
  63360. * A ShadowGenerator is the required tool to use the shadows.
  63361. * Each light casting shadows needs to use its own ShadowGenerator.
  63362. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  63363. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  63364. * @param light The light object generating the shadows.
  63365. * @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.
  63366. */
  63367. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  63368. this._bias = 0.00005;
  63369. this._normalBias = 0;
  63370. this._blurBoxOffset = 1;
  63371. this._blurScale = 2;
  63372. this._blurKernel = 1;
  63373. this._useKernelBlur = false;
  63374. this._filter = ShadowGenerator.FILTER_NONE;
  63375. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  63376. this._contactHardeningLightSizeUVRatio = 0.1;
  63377. this._darkness = 0;
  63378. this._transparencyShadow = false;
  63379. /**
  63380. * Controls the extent to which the shadows fade out at the edge of the frustum
  63381. * Used only by directionals and spots
  63382. */
  63383. this.frustumEdgeFalloff = 0;
  63384. /**
  63385. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  63386. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  63387. * It might on the other hand introduce peter panning.
  63388. */
  63389. this.forceBackFacesOnly = false;
  63390. this._lightDirection = BABYLON.Vector3.Zero();
  63391. this._viewMatrix = BABYLON.Matrix.Zero();
  63392. this._projectionMatrix = BABYLON.Matrix.Zero();
  63393. this._transformMatrix = BABYLON.Matrix.Zero();
  63394. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63395. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63396. this._currentFaceIndex = 0;
  63397. this._currentFaceIndexCache = 0;
  63398. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  63399. this._mapSize = mapSize;
  63400. this._light = light;
  63401. this._scene = light.getScene();
  63402. light._shadowGenerator = this;
  63403. // Texture type fallback from float to int if not supported.
  63404. var caps = this._scene.getEngine().getCaps();
  63405. if (!useFullFloatFirst) {
  63406. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63407. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63408. }
  63409. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63410. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63411. }
  63412. else {
  63413. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63414. }
  63415. }
  63416. else {
  63417. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63418. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63419. }
  63420. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63421. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63422. }
  63423. else {
  63424. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63425. }
  63426. }
  63427. this._initializeGenerator();
  63428. this._applyFilterValues();
  63429. }
  63430. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  63431. /**
  63432. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  63433. */
  63434. get: function () {
  63435. return this._bias;
  63436. },
  63437. /**
  63438. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  63439. */
  63440. set: function (bias) {
  63441. this._bias = bias;
  63442. },
  63443. enumerable: true,
  63444. configurable: true
  63445. });
  63446. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  63447. /**
  63448. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63449. */
  63450. get: function () {
  63451. return this._normalBias;
  63452. },
  63453. /**
  63454. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63455. */
  63456. set: function (normalBias) {
  63457. this._normalBias = normalBias;
  63458. },
  63459. enumerable: true,
  63460. configurable: true
  63461. });
  63462. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  63463. /**
  63464. * Gets the blur box offset: offset applied during the blur pass.
  63465. * Only usefull if useKernelBlur = false
  63466. */
  63467. get: function () {
  63468. return this._blurBoxOffset;
  63469. },
  63470. /**
  63471. * Sets the blur box offset: offset applied during the blur pass.
  63472. * Only usefull if useKernelBlur = false
  63473. */
  63474. set: function (value) {
  63475. if (this._blurBoxOffset === value) {
  63476. return;
  63477. }
  63478. this._blurBoxOffset = value;
  63479. this._disposeBlurPostProcesses();
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  63485. /**
  63486. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  63487. * 2 means half of the size.
  63488. */
  63489. get: function () {
  63490. return this._blurScale;
  63491. },
  63492. /**
  63493. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  63494. * 2 means half of the size.
  63495. */
  63496. set: function (value) {
  63497. if (this._blurScale === value) {
  63498. return;
  63499. }
  63500. this._blurScale = value;
  63501. this._disposeBlurPostProcesses();
  63502. },
  63503. enumerable: true,
  63504. configurable: true
  63505. });
  63506. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  63507. /**
  63508. * Gets the blur kernel: kernel size of the blur pass.
  63509. * Only usefull if useKernelBlur = true
  63510. */
  63511. get: function () {
  63512. return this._blurKernel;
  63513. },
  63514. /**
  63515. * Sets the blur kernel: kernel size of the blur pass.
  63516. * Only usefull if useKernelBlur = true
  63517. */
  63518. set: function (value) {
  63519. if (this._blurKernel === value) {
  63520. return;
  63521. }
  63522. this._blurKernel = value;
  63523. this._disposeBlurPostProcesses();
  63524. },
  63525. enumerable: true,
  63526. configurable: true
  63527. });
  63528. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  63529. /**
  63530. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  63531. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63532. */
  63533. get: function () {
  63534. return this._useKernelBlur;
  63535. },
  63536. /**
  63537. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  63538. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63539. */
  63540. set: function (value) {
  63541. if (this._useKernelBlur === value) {
  63542. return;
  63543. }
  63544. this._useKernelBlur = value;
  63545. this._disposeBlurPostProcesses();
  63546. },
  63547. enumerable: true,
  63548. configurable: true
  63549. });
  63550. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  63551. /**
  63552. * Gets the depth scale used in ESM mode.
  63553. */
  63554. get: function () {
  63555. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  63556. },
  63557. /**
  63558. * Sets the depth scale used in ESM mode.
  63559. * This can override the scale stored on the light.
  63560. */
  63561. set: function (value) {
  63562. this._depthScale = value;
  63563. },
  63564. enumerable: true,
  63565. configurable: true
  63566. });
  63567. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  63568. /**
  63569. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  63570. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63571. */
  63572. get: function () {
  63573. return this._filter;
  63574. },
  63575. /**
  63576. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  63577. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63578. */
  63579. set: function (value) {
  63580. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  63581. if (this._light.needCube()) {
  63582. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63583. this.useExponentialShadowMap = true;
  63584. return;
  63585. }
  63586. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63587. this.useCloseExponentialShadowMap = true;
  63588. return;
  63589. }
  63590. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63591. this.usePoissonSampling = true;
  63592. return;
  63593. }
  63594. }
  63595. // Weblg1 fallback for PCF.
  63596. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63597. if (this._scene.getEngine().webGLVersion === 1) {
  63598. this.usePoissonSampling = true;
  63599. return;
  63600. }
  63601. }
  63602. if (this._filter === value) {
  63603. return;
  63604. }
  63605. this._filter = value;
  63606. this._disposeBlurPostProcesses();
  63607. this._applyFilterValues();
  63608. this._light._markMeshesAsLightDirty();
  63609. },
  63610. enumerable: true,
  63611. configurable: true
  63612. });
  63613. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  63614. /**
  63615. * Gets if the current filter is set to Poisson Sampling.
  63616. */
  63617. get: function () {
  63618. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  63619. },
  63620. /**
  63621. * Sets the current filter to Poisson Sampling.
  63622. */
  63623. set: function (value) {
  63624. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  63625. return;
  63626. }
  63627. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  63628. },
  63629. enumerable: true,
  63630. configurable: true
  63631. });
  63632. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  63633. /**
  63634. * Gets if the current filter is set to VSM.
  63635. * DEPRECATED. Should use useExponentialShadowMap instead.
  63636. */
  63637. get: function () {
  63638. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  63639. return this.useExponentialShadowMap;
  63640. },
  63641. /**
  63642. * Sets the current filter is to VSM.
  63643. * DEPRECATED. Should use useExponentialShadowMap instead.
  63644. */
  63645. set: function (value) {
  63646. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  63647. this.useExponentialShadowMap = value;
  63648. },
  63649. enumerable: true,
  63650. configurable: true
  63651. });
  63652. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  63653. /**
  63654. * Gets if the current filter is set to blurred VSM.
  63655. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  63656. */
  63657. get: function () {
  63658. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  63659. return this.useBlurExponentialShadowMap;
  63660. },
  63661. /**
  63662. * Sets the current filter is to blurred VSM.
  63663. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  63664. */
  63665. set: function (value) {
  63666. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  63667. this.useBlurExponentialShadowMap = value;
  63668. },
  63669. enumerable: true,
  63670. configurable: true
  63671. });
  63672. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  63673. /**
  63674. * Gets if the current filter is set to ESM.
  63675. */
  63676. get: function () {
  63677. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  63678. },
  63679. /**
  63680. * Sets the current filter is to ESM.
  63681. */
  63682. set: function (value) {
  63683. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  63684. return;
  63685. }
  63686. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63687. },
  63688. enumerable: true,
  63689. configurable: true
  63690. });
  63691. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  63692. /**
  63693. * Gets if the current filter is set to filtered ESM.
  63694. */
  63695. get: function () {
  63696. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  63697. },
  63698. /**
  63699. * Gets if the current filter is set to filtered ESM.
  63700. */
  63701. set: function (value) {
  63702. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63703. return;
  63704. }
  63705. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63706. },
  63707. enumerable: true,
  63708. configurable: true
  63709. });
  63710. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  63711. /**
  63712. * Gets if the current filter is set to "close ESM" (using the inverse of the
  63713. * exponential to prevent steep falloff artifacts).
  63714. */
  63715. get: function () {
  63716. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  63717. },
  63718. /**
  63719. * Sets the current filter to "close ESM" (using the inverse of the
  63720. * exponential to prevent steep falloff artifacts).
  63721. */
  63722. set: function (value) {
  63723. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  63724. return;
  63725. }
  63726. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63727. },
  63728. enumerable: true,
  63729. configurable: true
  63730. });
  63731. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  63732. /**
  63733. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  63734. * exponential to prevent steep falloff artifacts).
  63735. */
  63736. get: function () {
  63737. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  63738. },
  63739. /**
  63740. * Sets the current filter to filtered "close ESM" (using the inverse of the
  63741. * exponential to prevent steep falloff artifacts).
  63742. */
  63743. set: function (value) {
  63744. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63745. return;
  63746. }
  63747. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63748. },
  63749. enumerable: true,
  63750. configurable: true
  63751. });
  63752. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  63753. /**
  63754. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  63755. */
  63756. get: function () {
  63757. return this.filter === ShadowGenerator.FILTER_PCF;
  63758. },
  63759. /**
  63760. * Sets the current filter to "PCF" (percentage closer filtering).
  63761. */
  63762. set: function (value) {
  63763. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  63764. return;
  63765. }
  63766. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  63767. },
  63768. enumerable: true,
  63769. configurable: true
  63770. });
  63771. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  63772. /**
  63773. * Gets the PCF or PCSS Quality.
  63774. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  63775. */
  63776. get: function () {
  63777. return this._filteringQuality;
  63778. },
  63779. /**
  63780. * Sets the PCF or PCSS Quality.
  63781. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  63782. */
  63783. set: function (filteringQuality) {
  63784. this._filteringQuality = filteringQuality;
  63785. },
  63786. enumerable: true,
  63787. configurable: true
  63788. });
  63789. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  63790. /**
  63791. * Gets if the current filter is set to "PCSS" (contact hardening).
  63792. */
  63793. get: function () {
  63794. return this.filter === ShadowGenerator.FILTER_PCSS;
  63795. },
  63796. /**
  63797. * Sets the current filter to "PCSS" (contact hardening).
  63798. */
  63799. set: function (value) {
  63800. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  63801. return;
  63802. }
  63803. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  63804. },
  63805. enumerable: true,
  63806. configurable: true
  63807. });
  63808. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  63809. /**
  63810. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  63811. * Using a ratio helps keeping shape stability independently of the map size.
  63812. *
  63813. * It does not account for the light projection as it was having too much
  63814. * instability during the light setup or during light position changes.
  63815. *
  63816. * Only valid if useContactHardeningShadow is true.
  63817. */
  63818. get: function () {
  63819. return this._contactHardeningLightSizeUVRatio;
  63820. },
  63821. /**
  63822. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  63823. * Using a ratio helps keeping shape stability independently of the map size.
  63824. *
  63825. * It does not account for the light projection as it was having too much
  63826. * instability during the light setup or during light position changes.
  63827. *
  63828. * Only valid if useContactHardeningShadow is true.
  63829. */
  63830. set: function (contactHardeningLightSizeUVRatio) {
  63831. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  63832. },
  63833. enumerable: true,
  63834. configurable: true
  63835. });
  63836. /**
  63837. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  63838. * 0 means strongest and 1 would means no shadow.
  63839. * @returns the darkness.
  63840. */
  63841. ShadowGenerator.prototype.getDarkness = function () {
  63842. return this._darkness;
  63843. };
  63844. /**
  63845. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  63846. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  63847. * @returns the shadow generator allowing fluent coding.
  63848. */
  63849. ShadowGenerator.prototype.setDarkness = function (darkness) {
  63850. if (darkness >= 1.0)
  63851. this._darkness = 1.0;
  63852. else if (darkness <= 0.0)
  63853. this._darkness = 0.0;
  63854. else
  63855. this._darkness = darkness;
  63856. return this;
  63857. };
  63858. /**
  63859. * Sets the ability to have transparent shadow (boolean).
  63860. * @param transparent True if transparent else False
  63861. * @returns the shadow generator allowing fluent coding
  63862. */
  63863. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  63864. this._transparencyShadow = transparent;
  63865. return this;
  63866. };
  63867. /**
  63868. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  63869. * @returns The render target texture if present otherwise, null
  63870. */
  63871. ShadowGenerator.prototype.getShadowMap = function () {
  63872. return this._shadowMap;
  63873. };
  63874. /**
  63875. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  63876. * @returns The render target texture if the shadow map is present otherwise, null
  63877. */
  63878. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  63879. if (this._shadowMap2) {
  63880. return this._shadowMap2;
  63881. }
  63882. return this._shadowMap;
  63883. };
  63884. /**
  63885. * Helper function to add a mesh and its descendants to the list of shadow casters.
  63886. * @param mesh Mesh to add
  63887. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  63888. * @returns the Shadow Generator itself
  63889. */
  63890. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  63891. if (includeDescendants === void 0) { includeDescendants = true; }
  63892. if (!this._shadowMap) {
  63893. return this;
  63894. }
  63895. if (!this._shadowMap.renderList) {
  63896. this._shadowMap.renderList = [];
  63897. }
  63898. this._shadowMap.renderList.push(mesh);
  63899. if (includeDescendants) {
  63900. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  63901. }
  63902. return this;
  63903. var _a;
  63904. };
  63905. /**
  63906. * Helper function to remove a mesh and its descendants from the list of shadow casters
  63907. * @param mesh Mesh to remove
  63908. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  63909. * @returns the Shadow Generator itself
  63910. */
  63911. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  63912. if (includeDescendants === void 0) { includeDescendants = true; }
  63913. if (!this._shadowMap || !this._shadowMap.renderList) {
  63914. return this;
  63915. }
  63916. var index = this._shadowMap.renderList.indexOf(mesh);
  63917. if (index !== -1) {
  63918. this._shadowMap.renderList.splice(index, 1);
  63919. }
  63920. if (includeDescendants) {
  63921. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  63922. var child = _a[_i];
  63923. this.removeShadowCaster(child);
  63924. }
  63925. }
  63926. return this;
  63927. };
  63928. /**
  63929. * Returns the associated light object.
  63930. * @returns the light generating the shadow
  63931. */
  63932. ShadowGenerator.prototype.getLight = function () {
  63933. return this._light;
  63934. };
  63935. ShadowGenerator.prototype._initializeGenerator = function () {
  63936. this._light._markMeshesAsLightDirty();
  63937. this._initializeShadowMap();
  63938. };
  63939. ShadowGenerator.prototype._initializeShadowMap = function () {
  63940. var _this = this;
  63941. // Render target
  63942. var engine = this._scene.getEngine();
  63943. if (engine.webGLVersion > 1) {
  63944. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  63945. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  63946. }
  63947. else {
  63948. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  63949. }
  63950. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63951. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63952. this._shadowMap.anisotropicFilteringLevel = 1;
  63953. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63954. this._shadowMap.renderParticles = false;
  63955. this._shadowMap.ignoreCameraViewport = true;
  63956. // Record Face Index before render.
  63957. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  63958. _this._currentFaceIndex = faceIndex;
  63959. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63960. engine.setColorWrite(false);
  63961. }
  63962. });
  63963. // Custom render function.
  63964. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  63965. // Blur if required afer render.
  63966. this._shadowMap.onAfterUnbindObservable.add(function () {
  63967. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63968. engine.setColorWrite(true);
  63969. }
  63970. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  63971. return;
  63972. }
  63973. var shadowMap = _this.getShadowMapForRendering();
  63974. if (shadowMap) {
  63975. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  63976. }
  63977. });
  63978. // Clear according to the chosen filter.
  63979. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  63980. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  63981. this._shadowMap.onClearObservable.add(function (engine) {
  63982. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63983. engine.clear(clearOne, false, true, false);
  63984. }
  63985. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  63986. engine.clear(clearZero, true, true, false);
  63987. }
  63988. else {
  63989. engine.clear(clearOne, true, true, false);
  63990. }
  63991. });
  63992. };
  63993. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  63994. var _this = this;
  63995. var engine = this._scene.getEngine();
  63996. var targetSize = this._mapSize / this.blurScale;
  63997. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  63998. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  63999. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64000. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64001. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64002. }
  64003. if (this.useKernelBlur) {
  64004. 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);
  64005. this._kernelBlurXPostprocess.width = targetSize;
  64006. this._kernelBlurXPostprocess.height = targetSize;
  64007. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64008. effect.setTexture("textureSampler", _this._shadowMap);
  64009. });
  64010. 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);
  64011. this._kernelBlurXPostprocess.autoClear = false;
  64012. this._kernelBlurYPostprocess.autoClear = false;
  64013. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64014. this._kernelBlurXPostprocess.packedFloat = true;
  64015. this._kernelBlurYPostprocess.packedFloat = true;
  64016. }
  64017. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64018. }
  64019. else {
  64020. 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);
  64021. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64022. effect.setFloat2("screenSize", targetSize, targetSize);
  64023. effect.setTexture("textureSampler", _this._shadowMap);
  64024. });
  64025. this._boxBlurPostprocess.autoClear = false;
  64026. this._blurPostProcesses = [this._boxBlurPostprocess];
  64027. }
  64028. };
  64029. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64030. var index;
  64031. var engine = this._scene.getEngine();
  64032. if (depthOnlySubMeshes.length) {
  64033. engine.setColorWrite(false);
  64034. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64035. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64036. }
  64037. engine.setColorWrite(true);
  64038. }
  64039. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64040. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64041. }
  64042. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64043. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64044. }
  64045. if (this._transparencyShadow) {
  64046. for (index = 0; index < transparentSubMeshes.length; index++) {
  64047. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  64048. }
  64049. }
  64050. };
  64051. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  64052. var _this = this;
  64053. var mesh = subMesh.getRenderingMesh();
  64054. var scene = this._scene;
  64055. var engine = scene.getEngine();
  64056. var material = subMesh.getMaterial();
  64057. if (!material) {
  64058. return;
  64059. }
  64060. // Culling
  64061. engine.setState(material.backFaceCulling);
  64062. // Managing instances
  64063. var batch = mesh._getInstancesRenderList(subMesh._id);
  64064. if (batch.mustReturn) {
  64065. return;
  64066. }
  64067. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64068. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  64069. engine.enableEffect(this._effect);
  64070. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  64071. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  64072. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  64073. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64074. this._effect.setVector3("lightData", this._cachedDirection);
  64075. }
  64076. else {
  64077. this._effect.setVector3("lightData", this._cachedPosition);
  64078. }
  64079. if (scene.activeCamera) {
  64080. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64081. }
  64082. // Alpha test
  64083. if (material && material.needAlphaTesting()) {
  64084. var alphaTexture = material.getAlphaTestTexture();
  64085. if (alphaTexture) {
  64086. this._effect.setTexture("diffuseSampler", alphaTexture);
  64087. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64088. }
  64089. }
  64090. // Bones
  64091. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64092. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64093. }
  64094. // Morph targets
  64095. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64096. if (this.forceBackFacesOnly) {
  64097. engine.setState(true, 0, false, true);
  64098. }
  64099. // Draw
  64100. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64101. if (this.forceBackFacesOnly) {
  64102. engine.setState(true, 0, false, false);
  64103. }
  64104. }
  64105. else {
  64106. // Need to reset refresh rate of the shadowMap
  64107. if (this._shadowMap) {
  64108. this._shadowMap.resetRefreshCounter();
  64109. }
  64110. }
  64111. };
  64112. ShadowGenerator.prototype._applyFilterValues = function () {
  64113. if (!this._shadowMap) {
  64114. return;
  64115. }
  64116. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64117. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64118. }
  64119. else {
  64120. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64121. }
  64122. };
  64123. /**
  64124. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64125. * @param onCompiled Callback triggered at the and of the effects compilation
  64126. * @param options Sets of optional options forcing the compilation with different modes
  64127. */
  64128. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64129. var _this = this;
  64130. var localOptions = __assign({ useInstances: false }, options);
  64131. var shadowMap = this.getShadowMap();
  64132. if (!shadowMap) {
  64133. if (onCompiled) {
  64134. onCompiled(this);
  64135. }
  64136. return;
  64137. }
  64138. var renderList = shadowMap.renderList;
  64139. if (!renderList) {
  64140. if (onCompiled) {
  64141. onCompiled(this);
  64142. }
  64143. return;
  64144. }
  64145. var subMeshes = new Array();
  64146. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64147. var mesh = renderList_1[_i];
  64148. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64149. }
  64150. if (subMeshes.length === 0) {
  64151. if (onCompiled) {
  64152. onCompiled(this);
  64153. }
  64154. return;
  64155. }
  64156. var currentIndex = 0;
  64157. var checkReady = function () {
  64158. if (!_this._scene || !_this._scene.getEngine()) {
  64159. return;
  64160. }
  64161. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64162. currentIndex++;
  64163. if (currentIndex >= subMeshes.length) {
  64164. if (onCompiled) {
  64165. onCompiled(_this);
  64166. }
  64167. return;
  64168. }
  64169. }
  64170. setTimeout(checkReady, 16);
  64171. };
  64172. checkReady();
  64173. };
  64174. /**
  64175. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64176. * @param options Sets of optional options forcing the compilation with different modes
  64177. * @returns A promise that resolves when the compilation completes
  64178. */
  64179. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64180. var _this = this;
  64181. return new Promise(function (resolve) {
  64182. _this.forceCompilation(function () {
  64183. resolve();
  64184. }, options);
  64185. });
  64186. };
  64187. /**
  64188. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64189. * @param subMesh The submesh we want to render in the shadow map
  64190. * @param useInstances Defines wether will draw in the map using instances
  64191. * @returns true if ready otherwise, false
  64192. */
  64193. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64194. var defines = [];
  64195. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64196. defines.push("#define FLOAT");
  64197. }
  64198. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64199. defines.push("#define ESM");
  64200. }
  64201. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64202. defines.push("#define DEPTHTEXTURE");
  64203. }
  64204. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64205. var mesh = subMesh.getMesh();
  64206. var material = subMesh.getMaterial();
  64207. // Normal bias.
  64208. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64209. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64210. defines.push("#define NORMAL");
  64211. if (mesh.nonUniformScaling) {
  64212. defines.push("#define NONUNIFORMSCALING");
  64213. }
  64214. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64215. defines.push("#define DIRECTIONINLIGHTDATA");
  64216. }
  64217. }
  64218. // Alpha test
  64219. if (material && material.needAlphaTesting()) {
  64220. var alphaTexture = material.getAlphaTestTexture();
  64221. if (alphaTexture) {
  64222. defines.push("#define ALPHATEST");
  64223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64224. attribs.push(BABYLON.VertexBuffer.UVKind);
  64225. defines.push("#define UV1");
  64226. }
  64227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64228. if (alphaTexture.coordinatesIndex === 1) {
  64229. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64230. defines.push("#define UV2");
  64231. }
  64232. }
  64233. }
  64234. }
  64235. // Bones
  64236. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64239. if (mesh.numBoneInfluencers > 4) {
  64240. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64241. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64242. }
  64243. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64244. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64245. }
  64246. else {
  64247. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64248. }
  64249. // Morph targets
  64250. var manager = mesh.morphTargetManager;
  64251. var morphInfluencers = 0;
  64252. if (manager) {
  64253. if (manager.numInfluencers > 0) {
  64254. defines.push("#define MORPHTARGETS");
  64255. morphInfluencers = manager.numInfluencers;
  64256. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  64257. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  64258. }
  64259. }
  64260. // Instances
  64261. if (useInstances) {
  64262. defines.push("#define INSTANCES");
  64263. attribs.push("world0");
  64264. attribs.push("world1");
  64265. attribs.push("world2");
  64266. attribs.push("world3");
  64267. }
  64268. // Get correct effect
  64269. var join = defines.join("\n");
  64270. if (this._cachedDefines !== join) {
  64271. this._cachedDefines = join;
  64272. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  64273. }
  64274. if (!this._effect.isReady()) {
  64275. return false;
  64276. }
  64277. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64278. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  64279. this._initializeBlurRTTAndPostProcesses();
  64280. }
  64281. }
  64282. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  64283. return false;
  64284. }
  64285. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  64286. return false;
  64287. }
  64288. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  64289. return false;
  64290. }
  64291. return true;
  64292. };
  64293. /**
  64294. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  64295. * @param defines Defines of the material we want to update
  64296. * @param lightIndex Index of the light in the enabled light list of the material
  64297. */
  64298. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  64299. var scene = this._scene;
  64300. var light = this._light;
  64301. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64302. return;
  64303. }
  64304. defines["SHADOW" + lightIndex] = true;
  64305. if (this.useContactHardeningShadow) {
  64306. defines["SHADOWPCSS" + lightIndex] = true;
  64307. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64308. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64309. }
  64310. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64311. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64312. }
  64313. // else default to high.
  64314. }
  64315. if (this.usePercentageCloserFiltering) {
  64316. defines["SHADOWPCF" + lightIndex] = true;
  64317. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64318. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64319. }
  64320. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64321. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64322. }
  64323. // else default to high.
  64324. }
  64325. else if (this.usePoissonSampling) {
  64326. defines["SHADOWPOISSON" + lightIndex] = true;
  64327. }
  64328. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64329. defines["SHADOWESM" + lightIndex] = true;
  64330. }
  64331. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64332. defines["SHADOWCLOSEESM" + lightIndex] = true;
  64333. }
  64334. if (light.needCube()) {
  64335. defines["SHADOWCUBE" + lightIndex] = true;
  64336. }
  64337. };
  64338. /**
  64339. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  64340. * defined in the generator but impacting the effect).
  64341. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  64342. * @param effect The effect we are binfing the information for
  64343. */
  64344. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  64345. var light = this._light;
  64346. var scene = this._scene;
  64347. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64348. return;
  64349. }
  64350. var camera = scene.activeCamera;
  64351. if (!camera) {
  64352. return;
  64353. }
  64354. var shadowMap = this.getShadowMap();
  64355. if (!shadowMap) {
  64356. return;
  64357. }
  64358. if (!light.needCube()) {
  64359. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  64360. }
  64361. // Only PCF uses depth stencil texture.
  64362. if (this._filter === ShadowGenerator.FILTER_PCF) {
  64363. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64364. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64365. }
  64366. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  64367. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64368. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  64369. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64370. }
  64371. else {
  64372. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64373. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  64374. }
  64375. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  64376. };
  64377. /**
  64378. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  64379. * (eq to shadow prjection matrix * light transform matrix)
  64380. * @returns The transform matrix used to create the shadow map
  64381. */
  64382. ShadowGenerator.prototype.getTransformMatrix = function () {
  64383. var scene = this._scene;
  64384. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  64385. return this._transformMatrix;
  64386. }
  64387. this._currentRenderID = scene.getRenderId();
  64388. this._currentFaceIndexCache = this._currentFaceIndex;
  64389. var lightPosition = this._light.position;
  64390. if (this._light.computeTransformedInformation()) {
  64391. lightPosition = this._light.transformedPosition;
  64392. }
  64393. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  64394. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  64395. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  64396. }
  64397. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  64398. this._cachedPosition.copyFrom(lightPosition);
  64399. this._cachedDirection.copyFrom(this._lightDirection);
  64400. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  64401. var shadowMap = this.getShadowMap();
  64402. if (shadowMap) {
  64403. var renderList = shadowMap.renderList;
  64404. if (renderList) {
  64405. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  64406. }
  64407. }
  64408. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  64409. }
  64410. return this._transformMatrix;
  64411. };
  64412. /**
  64413. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  64414. * Cube and 2D textures for instance.
  64415. */
  64416. ShadowGenerator.prototype.recreateShadowMap = function () {
  64417. var shadowMap = this._shadowMap;
  64418. if (!shadowMap) {
  64419. return;
  64420. }
  64421. // Track render list.
  64422. var renderList = shadowMap.renderList;
  64423. // Clean up existing data.
  64424. this._disposeRTTandPostProcesses();
  64425. // Reinitializes.
  64426. this._initializeGenerator();
  64427. // Reaffect the filter to ensure a correct fallback if necessary.
  64428. this.filter = this.filter;
  64429. // Reaffect the filter.
  64430. this._applyFilterValues();
  64431. // Reaffect Render List.
  64432. this._shadowMap.renderList = renderList;
  64433. };
  64434. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  64435. if (this._shadowMap2) {
  64436. this._shadowMap2.dispose();
  64437. this._shadowMap2 = null;
  64438. }
  64439. if (this._boxBlurPostprocess) {
  64440. this._boxBlurPostprocess.dispose();
  64441. this._boxBlurPostprocess = null;
  64442. }
  64443. if (this._kernelBlurXPostprocess) {
  64444. this._kernelBlurXPostprocess.dispose();
  64445. this._kernelBlurXPostprocess = null;
  64446. }
  64447. if (this._kernelBlurYPostprocess) {
  64448. this._kernelBlurYPostprocess.dispose();
  64449. this._kernelBlurYPostprocess = null;
  64450. }
  64451. this._blurPostProcesses = [];
  64452. };
  64453. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  64454. if (this._shadowMap) {
  64455. this._shadowMap.dispose();
  64456. this._shadowMap = null;
  64457. }
  64458. this._disposeBlurPostProcesses();
  64459. };
  64460. /**
  64461. * Disposes the ShadowGenerator.
  64462. * Returns nothing.
  64463. */
  64464. ShadowGenerator.prototype.dispose = function () {
  64465. this._disposeRTTandPostProcesses();
  64466. if (this._light) {
  64467. this._light._shadowGenerator = null;
  64468. this._light._markMeshesAsLightDirty();
  64469. }
  64470. };
  64471. /**
  64472. * Serializes the shadow generator setup to a json object.
  64473. * @returns The serialized JSON object
  64474. */
  64475. ShadowGenerator.prototype.serialize = function () {
  64476. var serializationObject = {};
  64477. var shadowMap = this.getShadowMap();
  64478. if (!shadowMap) {
  64479. return serializationObject;
  64480. }
  64481. serializationObject.lightId = this._light.id;
  64482. serializationObject.mapSize = shadowMap.getRenderSize();
  64483. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  64484. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  64485. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64486. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64487. serializationObject.usePoissonSampling = this.usePoissonSampling;
  64488. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  64489. serializationObject.depthScale = this.depthScale;
  64490. serializationObject.darkness = this.getDarkness();
  64491. serializationObject.blurBoxOffset = this.blurBoxOffset;
  64492. serializationObject.blurKernel = this.blurKernel;
  64493. serializationObject.blurScale = this.blurScale;
  64494. serializationObject.useKernelBlur = this.useKernelBlur;
  64495. serializationObject.transparencyShadow = this._transparencyShadow;
  64496. serializationObject.bias = this.bias;
  64497. serializationObject.normalBias = this.normalBias;
  64498. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  64499. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  64500. serializationObject.filteringQuality = this.filteringQuality;
  64501. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  64502. serializationObject.renderList = [];
  64503. if (shadowMap.renderList) {
  64504. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  64505. var mesh = shadowMap.renderList[meshIndex];
  64506. serializationObject.renderList.push(mesh.id);
  64507. }
  64508. }
  64509. return serializationObject;
  64510. };
  64511. /**
  64512. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  64513. * @param parsedShadowGenerator The JSON object to parse
  64514. * @param scene The scene to create the shadow map for
  64515. * @returns The parsed shadow generator
  64516. */
  64517. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  64518. //casting to point light, as light is missing the position attr and typescript complains.
  64519. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  64520. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  64521. var shadowMap = shadowGenerator.getShadowMap();
  64522. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  64523. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  64524. meshes.forEach(function (mesh) {
  64525. if (!shadowMap) {
  64526. return;
  64527. }
  64528. if (!shadowMap.renderList) {
  64529. shadowMap.renderList = [];
  64530. }
  64531. shadowMap.renderList.push(mesh);
  64532. });
  64533. }
  64534. if (parsedShadowGenerator.usePoissonSampling) {
  64535. shadowGenerator.usePoissonSampling = true;
  64536. }
  64537. else if (parsedShadowGenerator.useExponentialShadowMap) {
  64538. shadowGenerator.useExponentialShadowMap = true;
  64539. }
  64540. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  64541. shadowGenerator.useBlurExponentialShadowMap = true;
  64542. }
  64543. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  64544. shadowGenerator.useCloseExponentialShadowMap = true;
  64545. }
  64546. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  64547. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  64548. }
  64549. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  64550. shadowGenerator.usePercentageCloserFiltering = true;
  64551. }
  64552. else if (parsedShadowGenerator.useContactHardeningShadow) {
  64553. shadowGenerator.useContactHardeningShadow = true;
  64554. }
  64555. if (parsedShadowGenerator.filteringQuality) {
  64556. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  64557. }
  64558. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  64559. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  64560. }
  64561. else if (parsedShadowGenerator.useVarianceShadowMap) {
  64562. shadowGenerator.useExponentialShadowMap = true;
  64563. }
  64564. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  64565. shadowGenerator.useBlurExponentialShadowMap = true;
  64566. }
  64567. if (parsedShadowGenerator.depthScale) {
  64568. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  64569. }
  64570. if (parsedShadowGenerator.blurScale) {
  64571. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  64572. }
  64573. if (parsedShadowGenerator.blurBoxOffset) {
  64574. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  64575. }
  64576. if (parsedShadowGenerator.useKernelBlur) {
  64577. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  64578. }
  64579. if (parsedShadowGenerator.blurKernel) {
  64580. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  64581. }
  64582. if (parsedShadowGenerator.bias !== undefined) {
  64583. shadowGenerator.bias = parsedShadowGenerator.bias;
  64584. }
  64585. if (parsedShadowGenerator.normalBias !== undefined) {
  64586. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  64587. }
  64588. if (parsedShadowGenerator.darkness) {
  64589. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  64590. }
  64591. if (parsedShadowGenerator.transparencyShadow) {
  64592. shadowGenerator.setTransparencyShadow(true);
  64593. }
  64594. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  64595. return shadowGenerator;
  64596. };
  64597. /**
  64598. * Shadow generator mode None: no filtering applied.
  64599. */
  64600. ShadowGenerator.FILTER_NONE = 0;
  64601. /**
  64602. * Shadow generator mode ESM: Exponential Shadow Mapping.
  64603. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64604. */
  64605. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  64606. /**
  64607. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  64608. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  64609. */
  64610. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  64611. /**
  64612. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  64613. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64614. */
  64615. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  64616. /**
  64617. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  64618. * edge artifacts on steep falloff.
  64619. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64620. */
  64621. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  64622. /**
  64623. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  64624. * edge artifacts on steep falloff.
  64625. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64626. */
  64627. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  64628. /**
  64629. * Shadow generator mode PCF: Percentage Closer Filtering
  64630. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  64631. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  64632. */
  64633. ShadowGenerator.FILTER_PCF = 6;
  64634. /**
  64635. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  64636. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  64637. * Contact Hardening
  64638. */
  64639. ShadowGenerator.FILTER_PCSS = 7;
  64640. /**
  64641. * Reserved for PCF and PCSS
  64642. * Highest Quality.
  64643. *
  64644. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  64645. *
  64646. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  64647. */
  64648. ShadowGenerator.QUALITY_HIGH = 0;
  64649. /**
  64650. * Reserved for PCF and PCSS
  64651. * Good tradeoff for quality/perf cross devices
  64652. *
  64653. * Execute PCF on a 3*3 kernel.
  64654. *
  64655. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  64656. */
  64657. ShadowGenerator.QUALITY_MEDIUM = 1;
  64658. /**
  64659. * Reserved for PCF and PCSS
  64660. * The lowest quality but the fastest.
  64661. *
  64662. * Execute PCF on a 1*1 kernel.
  64663. *
  64664. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  64665. */
  64666. ShadowGenerator.QUALITY_LOW = 2;
  64667. return ShadowGenerator;
  64668. }());
  64669. BABYLON.ShadowGenerator = ShadowGenerator;
  64670. })(BABYLON || (BABYLON = {}));
  64671. //# sourceMappingURL=babylon.shadowGenerator.js.map
  64672. "use strict";
  64673. var BABYLON;
  64674. (function (BABYLON) {
  64675. var DefaultLoadingScreen = /** @class */ (function () {
  64676. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  64677. if (_loadingText === void 0) { _loadingText = ""; }
  64678. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  64679. var _this = this;
  64680. this._renderingCanvas = _renderingCanvas;
  64681. this._loadingText = _loadingText;
  64682. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  64683. // Resize
  64684. this._resizeLoadingUI = function () {
  64685. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  64686. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  64687. if (!_this._loadingDiv) {
  64688. return;
  64689. }
  64690. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  64691. _this._loadingDiv.style.left = canvasRect.left + "px";
  64692. _this._loadingDiv.style.top = canvasRect.top + "px";
  64693. _this._loadingDiv.style.width = canvasRect.width + "px";
  64694. _this._loadingDiv.style.height = canvasRect.height + "px";
  64695. };
  64696. }
  64697. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  64698. if (this._loadingDiv) {
  64699. // Do not add a loading screen if there is already one
  64700. return;
  64701. }
  64702. this._loadingDiv = document.createElement("div");
  64703. this._loadingDiv.id = "babylonjsLoadingDiv";
  64704. this._loadingDiv.style.opacity = "0";
  64705. this._loadingDiv.style.transition = "opacity 1.5s ease";
  64706. this._loadingDiv.style.pointerEvents = "none";
  64707. // Loading text
  64708. this._loadingTextDiv = document.createElement("div");
  64709. this._loadingTextDiv.style.position = "absolute";
  64710. this._loadingTextDiv.style.left = "0";
  64711. this._loadingTextDiv.style.top = "50%";
  64712. this._loadingTextDiv.style.marginTop = "80px";
  64713. this._loadingTextDiv.style.width = "100%";
  64714. this._loadingTextDiv.style.height = "20px";
  64715. this._loadingTextDiv.style.fontFamily = "Arial";
  64716. this._loadingTextDiv.style.fontSize = "14px";
  64717. this._loadingTextDiv.style.color = "white";
  64718. this._loadingTextDiv.style.textAlign = "center";
  64719. this._loadingTextDiv.innerHTML = "Loading";
  64720. this._loadingDiv.appendChild(this._loadingTextDiv);
  64721. //set the predefined text
  64722. this._loadingTextDiv.innerHTML = this._loadingText;
  64723. // Generating keyframes
  64724. var style = document.createElement('style');
  64725. style.type = 'text/css';
  64726. 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 }";
  64727. style.innerHTML = keyFrames;
  64728. document.getElementsByTagName('head')[0].appendChild(style);
  64729. // Loading img
  64730. var imgBack = new Image();
  64731. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  64732. imgBack.style.position = "absolute";
  64733. imgBack.style.left = "50%";
  64734. imgBack.style.top = "50%";
  64735. imgBack.style.marginLeft = "-60px";
  64736. imgBack.style.marginTop = "-60px";
  64737. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  64738. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  64739. imgBack.style.transformOrigin = "50% 50%";
  64740. imgBack.style.webkitTransformOrigin = "50% 50%";
  64741. this._loadingDiv.appendChild(imgBack);
  64742. this._resizeLoadingUI();
  64743. window.addEventListener("resize", this._resizeLoadingUI);
  64744. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  64745. document.body.appendChild(this._loadingDiv);
  64746. this._loadingDiv.style.opacity = "1";
  64747. };
  64748. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  64749. var _this = this;
  64750. if (!this._loadingDiv) {
  64751. return;
  64752. }
  64753. var onTransitionEnd = function () {
  64754. if (!_this._loadingDiv) {
  64755. return;
  64756. }
  64757. document.body.removeChild(_this._loadingDiv);
  64758. window.removeEventListener("resize", _this._resizeLoadingUI);
  64759. _this._loadingDiv = null;
  64760. };
  64761. this._loadingDiv.style.opacity = "0";
  64762. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  64763. };
  64764. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  64765. set: function (text) {
  64766. this._loadingText = text;
  64767. if (this._loadingTextDiv) {
  64768. this._loadingTextDiv.innerHTML = this._loadingText;
  64769. }
  64770. },
  64771. enumerable: true,
  64772. configurable: true
  64773. });
  64774. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  64775. get: function () {
  64776. return this._loadingDivBackgroundColor;
  64777. },
  64778. set: function (color) {
  64779. this._loadingDivBackgroundColor = color;
  64780. if (!this._loadingDiv) {
  64781. return;
  64782. }
  64783. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  64784. },
  64785. enumerable: true,
  64786. configurable: true
  64787. });
  64788. return DefaultLoadingScreen;
  64789. }());
  64790. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  64791. })(BABYLON || (BABYLON = {}));
  64792. //# sourceMappingURL=babylon.loadingScreen.js.map
  64793. "use strict";
  64794. var BABYLON;
  64795. (function (BABYLON) {
  64796. var SceneLoaderProgressEvent = /** @class */ (function () {
  64797. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  64798. this.lengthComputable = lengthComputable;
  64799. this.loaded = loaded;
  64800. this.total = total;
  64801. }
  64802. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  64803. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  64804. };
  64805. return SceneLoaderProgressEvent;
  64806. }());
  64807. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  64808. var SceneLoader = /** @class */ (function () {
  64809. function SceneLoader() {
  64810. }
  64811. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  64812. get: function () {
  64813. return 0;
  64814. },
  64815. enumerable: true,
  64816. configurable: true
  64817. });
  64818. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  64819. get: function () {
  64820. return 1;
  64821. },
  64822. enumerable: true,
  64823. configurable: true
  64824. });
  64825. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  64826. get: function () {
  64827. return 2;
  64828. },
  64829. enumerable: true,
  64830. configurable: true
  64831. });
  64832. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  64833. get: function () {
  64834. return 3;
  64835. },
  64836. enumerable: true,
  64837. configurable: true
  64838. });
  64839. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  64840. get: function () {
  64841. return SceneLoader._ForceFullSceneLoadingForIncremental;
  64842. },
  64843. set: function (value) {
  64844. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  64845. },
  64846. enumerable: true,
  64847. configurable: true
  64848. });
  64849. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  64850. get: function () {
  64851. return SceneLoader._ShowLoadingScreen;
  64852. },
  64853. set: function (value) {
  64854. SceneLoader._ShowLoadingScreen = value;
  64855. },
  64856. enumerable: true,
  64857. configurable: true
  64858. });
  64859. Object.defineProperty(SceneLoader, "loggingLevel", {
  64860. get: function () {
  64861. return SceneLoader._loggingLevel;
  64862. },
  64863. set: function (value) {
  64864. SceneLoader._loggingLevel = value;
  64865. },
  64866. enumerable: true,
  64867. configurable: true
  64868. });
  64869. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  64870. get: function () {
  64871. return SceneLoader._CleanBoneMatrixWeights;
  64872. },
  64873. set: function (value) {
  64874. SceneLoader._CleanBoneMatrixWeights = value;
  64875. },
  64876. enumerable: true,
  64877. configurable: true
  64878. });
  64879. SceneLoader._getDefaultPlugin = function () {
  64880. return SceneLoader._registeredPlugins[".babylon"];
  64881. };
  64882. SceneLoader._getPluginForExtension = function (extension) {
  64883. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  64884. if (registeredPlugin) {
  64885. return registeredPlugin;
  64886. }
  64887. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  64888. return SceneLoader._getDefaultPlugin();
  64889. };
  64890. SceneLoader._getPluginForDirectLoad = function (data) {
  64891. for (var extension in SceneLoader._registeredPlugins) {
  64892. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  64893. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  64894. return SceneLoader._registeredPlugins[extension];
  64895. }
  64896. }
  64897. return SceneLoader._getDefaultPlugin();
  64898. };
  64899. SceneLoader._getPluginForFilename = function (sceneFilename) {
  64900. if (sceneFilename.name) {
  64901. sceneFilename = sceneFilename.name;
  64902. }
  64903. var queryStringPosition = sceneFilename.indexOf("?");
  64904. if (queryStringPosition !== -1) {
  64905. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  64906. }
  64907. var dotPosition = sceneFilename.lastIndexOf(".");
  64908. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  64909. return SceneLoader._getPluginForExtension(extension);
  64910. };
  64911. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  64912. SceneLoader._getDirectLoad = function (sceneFilename) {
  64913. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  64914. return sceneFilename.substr(5);
  64915. }
  64916. return null;
  64917. };
  64918. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  64919. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  64920. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  64921. var plugin;
  64922. if (registeredPlugin.plugin.createPlugin) {
  64923. plugin = registeredPlugin.plugin.createPlugin();
  64924. }
  64925. else {
  64926. plugin = registeredPlugin.plugin;
  64927. }
  64928. var useArrayBuffer = registeredPlugin.isBinary;
  64929. var database;
  64930. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  64931. var dataCallback = function (data, responseURL) {
  64932. if (scene.isDisposed) {
  64933. onError("Scene has been disposed");
  64934. return;
  64935. }
  64936. scene.database = database;
  64937. onSuccess(plugin, data, responseURL);
  64938. };
  64939. var request = null;
  64940. var pluginDisposed = false;
  64941. var onDisposeObservable = plugin.onDisposeObservable;
  64942. if (onDisposeObservable) {
  64943. onDisposeObservable.add(function () {
  64944. pluginDisposed = true;
  64945. if (request) {
  64946. request.abort();
  64947. request = null;
  64948. }
  64949. onDispose();
  64950. });
  64951. }
  64952. var manifestChecked = function () {
  64953. if (pluginDisposed) {
  64954. return;
  64955. }
  64956. var url = rootUrl + sceneFilename;
  64957. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  64958. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  64959. } : undefined, database, useArrayBuffer, function (request, exception) {
  64960. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  64961. });
  64962. };
  64963. if (directLoad) {
  64964. dataCallback(directLoad);
  64965. return plugin;
  64966. }
  64967. if (rootUrl.indexOf("file:") === -1) {
  64968. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  64969. if (canUseOfflineSupport) {
  64970. // Also check for exceptions
  64971. var exceptionFound = false;
  64972. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  64973. var regex = _a[_i];
  64974. if (regex.test(rootUrl + sceneFilename)) {
  64975. exceptionFound = true;
  64976. break;
  64977. }
  64978. }
  64979. canUseOfflineSupport = !exceptionFound;
  64980. }
  64981. if (canUseOfflineSupport) {
  64982. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  64983. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  64984. }
  64985. else {
  64986. manifestChecked();
  64987. }
  64988. }
  64989. else {
  64990. var fileOrString = sceneFilename;
  64991. if (fileOrString.name) {
  64992. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  64993. }
  64994. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  64995. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  64996. }
  64997. else {
  64998. onError("Unable to find file named " + sceneFilename);
  64999. }
  65000. }
  65001. return plugin;
  65002. };
  65003. // Public functions
  65004. SceneLoader.GetPluginForExtension = function (extension) {
  65005. return SceneLoader._getPluginForExtension(extension).plugin;
  65006. };
  65007. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65008. return !!SceneLoader._registeredPlugins[extension];
  65009. };
  65010. SceneLoader.RegisterPlugin = function (plugin) {
  65011. if (typeof plugin.extensions === "string") {
  65012. var extension = plugin.extensions;
  65013. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65014. plugin: plugin,
  65015. isBinary: false
  65016. };
  65017. }
  65018. else {
  65019. var extensions = plugin.extensions;
  65020. Object.keys(extensions).forEach(function (extension) {
  65021. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65022. plugin: plugin,
  65023. isBinary: extensions[extension].isBinary
  65024. };
  65025. });
  65026. }
  65027. };
  65028. /**
  65029. * Import meshes into a scene
  65030. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65031. * @param rootUrl a string that defines the root url for scene and resources
  65032. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65033. * @param scene the instance of BABYLON.Scene to append to
  65034. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65035. * @param onProgress a callback with a progress event for each file being loaded
  65036. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65037. * @param pluginExtension the extension used to determine the plugin
  65038. * @returns The loaded plugin
  65039. */
  65040. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65041. if (onSuccess === void 0) { onSuccess = null; }
  65042. if (onProgress === void 0) { onProgress = null; }
  65043. if (onError === void 0) { onError = null; }
  65044. if (pluginExtension === void 0) { pluginExtension = null; }
  65045. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65046. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65047. return null;
  65048. }
  65049. var loadingToken = {};
  65050. scene._addPendingData(loadingToken);
  65051. var disposeHandler = function () {
  65052. scene._removePendingData(loadingToken);
  65053. };
  65054. var errorHandler = function (message, exception) {
  65055. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  65056. if (onError) {
  65057. onError(scene, errorMessage, exception);
  65058. }
  65059. else {
  65060. BABYLON.Tools.Error(errorMessage);
  65061. // should the exception be thrown?
  65062. }
  65063. disposeHandler();
  65064. };
  65065. var progressHandler = onProgress ? function (event) {
  65066. try {
  65067. onProgress(event);
  65068. }
  65069. catch (e) {
  65070. errorHandler("Error in onProgress callback", e);
  65071. }
  65072. } : undefined;
  65073. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  65074. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  65075. if (onSuccess) {
  65076. try {
  65077. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  65078. }
  65079. catch (e) {
  65080. errorHandler("Error in onSuccess callback", e);
  65081. }
  65082. }
  65083. scene._removePendingData(loadingToken);
  65084. };
  65085. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65086. if (plugin.rewriteRootURL) {
  65087. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65088. }
  65089. if (sceneFilename === "") {
  65090. if (sceneFilename === "") {
  65091. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65092. }
  65093. }
  65094. if (plugin.importMesh) {
  65095. var syncedPlugin = plugin;
  65096. var meshes = new Array();
  65097. var particleSystems = new Array();
  65098. var skeletons = new Array();
  65099. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  65100. return;
  65101. }
  65102. scene.loadingPluginName = plugin.name;
  65103. successHandler(meshes, particleSystems, skeletons, []);
  65104. }
  65105. else {
  65106. var asyncedPlugin = plugin;
  65107. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65108. scene.loadingPluginName = plugin.name;
  65109. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65110. }).catch(function (error) {
  65111. errorHandler(error.message, error);
  65112. });
  65113. }
  65114. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65115. };
  65116. /**
  65117. * Import meshes into a scene
  65118. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65119. * @param rootUrl a string that defines the root url for scene and resources
  65120. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65121. * @param scene the instance of BABYLON.Scene to append to
  65122. * @param onProgress a callback with a progress event for each file being loaded
  65123. * @param pluginExtension the extension used to determine the plugin
  65124. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65125. */
  65126. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65127. if (onProgress === void 0) { onProgress = null; }
  65128. if (pluginExtension === void 0) { pluginExtension = null; }
  65129. return new Promise(function (resolve, reject) {
  65130. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65131. resolve({
  65132. meshes: meshes,
  65133. particleSystems: particleSystems,
  65134. skeletons: skeletons,
  65135. animationGroups: animationGroups
  65136. });
  65137. }, onProgress, function (scene, message, exception) {
  65138. reject(exception || new Error(message));
  65139. });
  65140. });
  65141. };
  65142. /**
  65143. * Load a scene
  65144. * @param rootUrl a string that defines the root url for scene and resources
  65145. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65146. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65147. * @param onSuccess a callback with the scene when import succeeds
  65148. * @param onProgress a callback with a progress event for each file being loaded
  65149. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65150. * @param pluginExtension the extension used to determine the plugin
  65151. * @returns The loaded plugin
  65152. */
  65153. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65154. if (onSuccess === void 0) { onSuccess = null; }
  65155. if (onProgress === void 0) { onProgress = null; }
  65156. if (onError === void 0) { onError = null; }
  65157. if (pluginExtension === void 0) { pluginExtension = null; }
  65158. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65159. };
  65160. /**
  65161. * Load a scene
  65162. * @param rootUrl a string that defines the root url for scene and resources
  65163. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65164. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65165. * @param onProgress a callback with a progress event for each file being loaded
  65166. * @param pluginExtension the extension used to determine the plugin
  65167. * @returns The loaded scene
  65168. */
  65169. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65170. if (onProgress === void 0) { onProgress = null; }
  65171. if (pluginExtension === void 0) { pluginExtension = null; }
  65172. return new Promise(function (resolve, reject) {
  65173. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65174. resolve(scene);
  65175. }, onProgress, function (scene, message, exception) {
  65176. reject(exception || new Error(message));
  65177. }, pluginExtension);
  65178. });
  65179. };
  65180. /**
  65181. * Append a scene
  65182. * @param rootUrl a string that defines the root url for scene and resources
  65183. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65184. * @param scene is the instance of BABYLON.Scene to append to
  65185. * @param onSuccess a callback with the scene when import succeeds
  65186. * @param onProgress a callback with a progress event for each file being loaded
  65187. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65188. * @param pluginExtension the extension used to determine the plugin
  65189. * @returns The loaded plugin
  65190. */
  65191. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65192. if (onSuccess === void 0) { onSuccess = null; }
  65193. if (onProgress === void 0) { onProgress = null; }
  65194. if (onError === void 0) { onError = null; }
  65195. if (pluginExtension === void 0) { pluginExtension = null; }
  65196. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65197. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65198. return null;
  65199. }
  65200. if (SceneLoader.ShowLoadingScreen) {
  65201. scene.getEngine().displayLoadingUI();
  65202. }
  65203. var loadingToken = {};
  65204. scene._addPendingData(loadingToken);
  65205. var disposeHandler = function () {
  65206. scene._removePendingData(loadingToken);
  65207. scene.getEngine().hideLoadingUI();
  65208. };
  65209. var errorHandler = function (message, exception) {
  65210. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65211. if (onError) {
  65212. onError(scene, errorMessage, exception);
  65213. }
  65214. else {
  65215. BABYLON.Tools.Error(errorMessage);
  65216. // should the exception be thrown?
  65217. }
  65218. disposeHandler();
  65219. };
  65220. var progressHandler = onProgress ? function (event) {
  65221. try {
  65222. onProgress(event);
  65223. }
  65224. catch (e) {
  65225. errorHandler("Error in onProgress callback", e);
  65226. }
  65227. } : undefined;
  65228. var successHandler = function () {
  65229. if (onSuccess) {
  65230. try {
  65231. onSuccess(scene);
  65232. }
  65233. catch (e) {
  65234. errorHandler("Error in onSuccess callback", e);
  65235. }
  65236. }
  65237. scene._removePendingData(loadingToken);
  65238. };
  65239. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65240. if (sceneFilename === "") {
  65241. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65242. }
  65243. if (plugin.load) {
  65244. var syncedPlugin = plugin;
  65245. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  65246. return;
  65247. }
  65248. scene.loadingPluginName = plugin.name;
  65249. successHandler();
  65250. }
  65251. else {
  65252. var asyncedPlugin = plugin;
  65253. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  65254. scene.loadingPluginName = plugin.name;
  65255. successHandler();
  65256. }).catch(function (error) {
  65257. errorHandler(error.message, error);
  65258. });
  65259. }
  65260. if (SceneLoader.ShowLoadingScreen) {
  65261. scene.executeWhenReady(function () {
  65262. scene.getEngine().hideLoadingUI();
  65263. });
  65264. }
  65265. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65266. };
  65267. /**
  65268. * Append a scene
  65269. * @param rootUrl a string that defines the root url for scene and resources
  65270. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65271. * @param scene is the instance of BABYLON.Scene to append to
  65272. * @param onProgress a callback with a progress event for each file being loaded
  65273. * @param pluginExtension the extension used to determine the plugin
  65274. * @returns The given scene
  65275. */
  65276. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65277. if (onProgress === void 0) { onProgress = null; }
  65278. if (pluginExtension === void 0) { pluginExtension = null; }
  65279. return new Promise(function (resolve, reject) {
  65280. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  65281. resolve(scene);
  65282. }, onProgress, function (scene, message, exception) {
  65283. reject(exception || new Error(message));
  65284. }, pluginExtension);
  65285. });
  65286. };
  65287. /**
  65288. * Load a scene into an asset container
  65289. * @param rootUrl a string that defines the root url for scene and resources
  65290. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65291. * @param scene is the instance of BABYLON.Scene to append to
  65292. * @param onSuccess a callback with the scene when import succeeds
  65293. * @param onProgress a callback with a progress event for each file being loaded
  65294. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65295. * @param pluginExtension the extension used to determine the plugin
  65296. * @returns The loaded plugin
  65297. */
  65298. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65299. if (onSuccess === void 0) { onSuccess = null; }
  65300. if (onProgress === void 0) { onProgress = null; }
  65301. if (onError === void 0) { onError = null; }
  65302. if (pluginExtension === void 0) { pluginExtension = null; }
  65303. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65304. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65305. return null;
  65306. }
  65307. var loadingToken = {};
  65308. scene._addPendingData(loadingToken);
  65309. var disposeHandler = function () {
  65310. scene._removePendingData(loadingToken);
  65311. };
  65312. var errorHandler = function (message, exception) {
  65313. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65314. if (onError) {
  65315. onError(scene, errorMessage, exception);
  65316. }
  65317. else {
  65318. BABYLON.Tools.Error(errorMessage);
  65319. // should the exception be thrown?
  65320. }
  65321. disposeHandler();
  65322. };
  65323. var progressHandler = onProgress ? function (event) {
  65324. try {
  65325. onProgress(event);
  65326. }
  65327. catch (e) {
  65328. errorHandler("Error in onProgress callback", e);
  65329. }
  65330. } : undefined;
  65331. var successHandler = function (assets) {
  65332. if (onSuccess) {
  65333. try {
  65334. onSuccess(assets);
  65335. }
  65336. catch (e) {
  65337. errorHandler("Error in onSuccess callback", e);
  65338. }
  65339. }
  65340. scene._removePendingData(loadingToken);
  65341. };
  65342. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65343. if (plugin.loadAssetContainer) {
  65344. var syncedPlugin = plugin;
  65345. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  65346. if (!assetContainer) {
  65347. return;
  65348. }
  65349. scene.loadingPluginName = plugin.name;
  65350. successHandler(assetContainer);
  65351. }
  65352. else if (plugin.loadAssetContainerAsync) {
  65353. var asyncedPlugin = plugin;
  65354. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  65355. scene.loadingPluginName = plugin.name;
  65356. successHandler(assetContainer);
  65357. }).catch(function (error) {
  65358. errorHandler(error.message, error);
  65359. });
  65360. }
  65361. else {
  65362. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  65363. }
  65364. if (SceneLoader.ShowLoadingScreen) {
  65365. scene.executeWhenReady(function () {
  65366. scene.getEngine().hideLoadingUI();
  65367. });
  65368. }
  65369. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65370. };
  65371. /**
  65372. * Load a scene into an asset container
  65373. * @param rootUrl a string that defines the root url for scene and resources
  65374. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65375. * @param scene is the instance of BABYLON.Scene to append to
  65376. * @param onProgress a callback with a progress event for each file being loaded
  65377. * @param pluginExtension the extension used to determine the plugin
  65378. * @returns The loaded asset container
  65379. */
  65380. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65381. if (onProgress === void 0) { onProgress = null; }
  65382. if (pluginExtension === void 0) { pluginExtension = null; }
  65383. return new Promise(function (resolve, reject) {
  65384. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  65385. resolve(assetContainer);
  65386. }, onProgress, function (scene, message, exception) {
  65387. reject(exception || new Error(message));
  65388. }, pluginExtension);
  65389. });
  65390. };
  65391. // Flags
  65392. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  65393. SceneLoader._ShowLoadingScreen = true;
  65394. SceneLoader._CleanBoneMatrixWeights = false;
  65395. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  65396. // Members
  65397. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  65398. SceneLoader._registeredPlugins = {};
  65399. return SceneLoader;
  65400. }());
  65401. BABYLON.SceneLoader = SceneLoader;
  65402. ;
  65403. })(BABYLON || (BABYLON = {}));
  65404. //# sourceMappingURL=babylon.sceneLoader.js.map
  65405. "use strict";
  65406. var BABYLON;
  65407. (function (BABYLON) {
  65408. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  65409. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65410. var parsedMaterial = parsedData.materials[index];
  65411. if (parsedMaterial.id === id) {
  65412. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65413. }
  65414. }
  65415. return null;
  65416. };
  65417. var isDescendantOf = function (mesh, names, hierarchyIds) {
  65418. for (var i in names) {
  65419. if (mesh.name === names[i]) {
  65420. hierarchyIds.push(mesh.id);
  65421. return true;
  65422. }
  65423. }
  65424. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  65425. hierarchyIds.push(mesh.id);
  65426. return true;
  65427. }
  65428. return false;
  65429. };
  65430. var logOperation = function (operation, producer) {
  65431. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  65432. };
  65433. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  65434. if (addToScene === void 0) { addToScene = false; }
  65435. var container = new BABYLON.AssetContainer(scene);
  65436. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65437. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65438. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65439. // and avoid problems with multiple concurrent .babylon loads.
  65440. var log = "importScene has failed JSON parse";
  65441. try {
  65442. var parsedData = JSON.parse(data);
  65443. log = "";
  65444. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65445. var index;
  65446. var cache;
  65447. // Lights
  65448. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  65449. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  65450. var parsedLight = parsedData.lights[index];
  65451. var light = BABYLON.Light.Parse(parsedLight, scene);
  65452. if (light) {
  65453. container.lights.push(light);
  65454. log += (index === 0 ? "\n\tLights:" : "");
  65455. log += "\n\t\t" + light.toString(fullDetails);
  65456. }
  65457. }
  65458. }
  65459. // Animations
  65460. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  65461. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  65462. var parsedAnimation = parsedData.animations[index];
  65463. var animation = BABYLON.Animation.Parse(parsedAnimation);
  65464. scene.animations.push(animation);
  65465. container.animations.push(animation);
  65466. log += (index === 0 ? "\n\tAnimations:" : "");
  65467. log += "\n\t\t" + animation.toString(fullDetails);
  65468. }
  65469. }
  65470. // Materials
  65471. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  65472. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65473. var parsedMaterial = parsedData.materials[index];
  65474. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65475. container.materials.push(mat);
  65476. log += (index === 0 ? "\n\tMaterials:" : "");
  65477. log += "\n\t\t" + mat.toString(fullDetails);
  65478. }
  65479. }
  65480. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65481. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  65482. var parsedMultiMaterial = parsedData.multiMaterials[index];
  65483. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65484. container.multiMaterials.push(mmat);
  65485. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  65486. log += "\n\t\t" + mmat.toString(fullDetails);
  65487. }
  65488. }
  65489. // Morph targets
  65490. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  65491. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  65492. var managerData = _a[_i];
  65493. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  65494. }
  65495. }
  65496. // Skeletons
  65497. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65498. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  65499. var parsedSkeleton = parsedData.skeletons[index];
  65500. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65501. container.skeletons.push(skeleton);
  65502. log += (index === 0 ? "\n\tSkeletons:" : "");
  65503. log += "\n\t\t" + skeleton.toString(fullDetails);
  65504. }
  65505. }
  65506. // Geometries
  65507. var geometries = parsedData.geometries;
  65508. if (geometries !== undefined && geometries !== null) {
  65509. var addedGeometry = new Array();
  65510. // Boxes
  65511. var boxes = geometries.boxes;
  65512. if (boxes !== undefined && boxes !== null) {
  65513. for (index = 0, cache = boxes.length; index < cache; index++) {
  65514. var parsedBox = boxes[index];
  65515. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  65516. }
  65517. }
  65518. // Spheres
  65519. var spheres = geometries.spheres;
  65520. if (spheres !== undefined && spheres !== null) {
  65521. for (index = 0, cache = spheres.length; index < cache; index++) {
  65522. var parsedSphere = spheres[index];
  65523. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  65524. }
  65525. }
  65526. // Cylinders
  65527. var cylinders = geometries.cylinders;
  65528. if (cylinders !== undefined && cylinders !== null) {
  65529. for (index = 0, cache = cylinders.length; index < cache; index++) {
  65530. var parsedCylinder = cylinders[index];
  65531. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  65532. }
  65533. }
  65534. // Toruses
  65535. var toruses = geometries.toruses;
  65536. if (toruses !== undefined && toruses !== null) {
  65537. for (index = 0, cache = toruses.length; index < cache; index++) {
  65538. var parsedTorus = toruses[index];
  65539. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  65540. }
  65541. }
  65542. // Grounds
  65543. var grounds = geometries.grounds;
  65544. if (grounds !== undefined && grounds !== null) {
  65545. for (index = 0, cache = grounds.length; index < cache; index++) {
  65546. var parsedGround = grounds[index];
  65547. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  65548. }
  65549. }
  65550. // Planes
  65551. var planes = geometries.planes;
  65552. if (planes !== undefined && planes !== null) {
  65553. for (index = 0, cache = planes.length; index < cache; index++) {
  65554. var parsedPlane = planes[index];
  65555. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  65556. }
  65557. }
  65558. // TorusKnots
  65559. var torusKnots = geometries.torusKnots;
  65560. if (torusKnots !== undefined && torusKnots !== null) {
  65561. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  65562. var parsedTorusKnot = torusKnots[index];
  65563. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  65564. }
  65565. }
  65566. // VertexData
  65567. var vertexData = geometries.vertexData;
  65568. if (vertexData !== undefined && vertexData !== null) {
  65569. for (index = 0, cache = vertexData.length; index < cache; index++) {
  65570. var parsedVertexData = vertexData[index];
  65571. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  65572. }
  65573. }
  65574. addedGeometry.forEach(function (g) {
  65575. if (g) {
  65576. container.geometries.push(g);
  65577. }
  65578. });
  65579. }
  65580. // Transform nodes
  65581. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  65582. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  65583. var parsedTransformNode = parsedData.transformNodes[index];
  65584. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  65585. container.transformNodes.push(node);
  65586. }
  65587. }
  65588. // Meshes
  65589. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65590. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65591. var parsedMesh = parsedData.meshes[index];
  65592. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65593. container.meshes.push(mesh);
  65594. log += (index === 0 ? "\n\tMeshes:" : "");
  65595. log += "\n\t\t" + mesh.toString(fullDetails);
  65596. }
  65597. }
  65598. // Cameras
  65599. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  65600. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  65601. var parsedCamera = parsedData.cameras[index];
  65602. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  65603. container.cameras.push(camera);
  65604. log += (index === 0 ? "\n\tCameras:" : "");
  65605. log += "\n\t\t" + camera.toString(fullDetails);
  65606. }
  65607. }
  65608. // Browsing all the graph to connect the dots
  65609. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  65610. var camera = scene.cameras[index];
  65611. if (camera._waitingParentId) {
  65612. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  65613. camera._waitingParentId = null;
  65614. }
  65615. }
  65616. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  65617. var light_1 = scene.lights[index];
  65618. if (light_1 && light_1._waitingParentId) {
  65619. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  65620. light_1._waitingParentId = null;
  65621. }
  65622. }
  65623. // Sounds
  65624. // TODO: add sound
  65625. var loadedSounds = [];
  65626. var loadedSound;
  65627. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  65628. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  65629. var parsedSound = parsedData.sounds[index];
  65630. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65631. if (!parsedSound.url)
  65632. parsedSound.url = parsedSound.name;
  65633. if (!loadedSounds[parsedSound.url]) {
  65634. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  65635. loadedSounds[parsedSound.url] = loadedSound;
  65636. container.sounds.push(loadedSound);
  65637. }
  65638. else {
  65639. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  65640. }
  65641. }
  65642. else {
  65643. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  65644. }
  65645. }
  65646. }
  65647. loadedSounds = [];
  65648. // Connect parents & children and parse actions
  65649. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  65650. var transformNode = scene.transformNodes[index];
  65651. if (transformNode._waitingParentId) {
  65652. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  65653. transformNode._waitingParentId = null;
  65654. }
  65655. }
  65656. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65657. var mesh = scene.meshes[index];
  65658. if (mesh._waitingParentId) {
  65659. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  65660. mesh._waitingParentId = null;
  65661. }
  65662. if (mesh._waitingActions) {
  65663. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  65664. mesh._waitingActions = null;
  65665. }
  65666. }
  65667. // freeze world matrix application
  65668. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65669. var currentMesh = scene.meshes[index];
  65670. if (currentMesh._waitingFreezeWorldMatrix) {
  65671. currentMesh.freezeWorldMatrix();
  65672. currentMesh._waitingFreezeWorldMatrix = null;
  65673. }
  65674. else {
  65675. currentMesh.computeWorldMatrix(true);
  65676. }
  65677. }
  65678. // Particles Systems
  65679. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  65680. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  65681. var parsedParticleSystem = parsedData.particleSystems[index];
  65682. if (parsedParticleSystem.activeParticleCount) {
  65683. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  65684. container.particleSystems.push(ps);
  65685. }
  65686. else {
  65687. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  65688. container.particleSystems.push(ps);
  65689. }
  65690. }
  65691. }
  65692. // Lens flares
  65693. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  65694. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  65695. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  65696. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  65697. container.lensFlareSystems.push(lf);
  65698. }
  65699. }
  65700. // Shadows
  65701. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  65702. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  65703. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  65704. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  65705. container.shadowGenerators.push(sg);
  65706. }
  65707. }
  65708. // Lights exclusions / inclusions
  65709. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  65710. var light_2 = scene.lights[index];
  65711. // Excluded check
  65712. if (light_2._excludedMeshesIds.length > 0) {
  65713. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  65714. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  65715. if (excludedMesh) {
  65716. light_2.excludedMeshes.push(excludedMesh);
  65717. }
  65718. }
  65719. light_2._excludedMeshesIds = [];
  65720. }
  65721. // Included check
  65722. if (light_2._includedOnlyMeshesIds.length > 0) {
  65723. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  65724. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  65725. if (includedOnlyMesh) {
  65726. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  65727. }
  65728. }
  65729. light_2._includedOnlyMeshesIds = [];
  65730. }
  65731. }
  65732. // Actions (scene)
  65733. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  65734. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  65735. }
  65736. if (!addToScene) {
  65737. container.removeAllFromScene();
  65738. }
  65739. }
  65740. catch (err) {
  65741. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  65742. if (onError) {
  65743. onError(msg, err);
  65744. }
  65745. else {
  65746. BABYLON.Tools.Log(msg);
  65747. throw err;
  65748. }
  65749. }
  65750. finally {
  65751. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65752. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65753. }
  65754. }
  65755. return container;
  65756. };
  65757. BABYLON.SceneLoader.RegisterPlugin({
  65758. name: "babylon.js",
  65759. extensions: ".babylon",
  65760. canDirectLoad: function (data) {
  65761. if (data.indexOf("babylon") !== -1) {
  65762. return true;
  65763. }
  65764. return false;
  65765. },
  65766. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  65767. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65768. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65769. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65770. // and avoid problems with multiple concurrent .babylon loads.
  65771. var log = "importMesh has failed JSON parse";
  65772. try {
  65773. var parsedData = JSON.parse(data);
  65774. log = "";
  65775. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65776. if (!meshesNames) {
  65777. meshesNames = null;
  65778. }
  65779. else if (!Array.isArray(meshesNames)) {
  65780. meshesNames = [meshesNames];
  65781. }
  65782. var hierarchyIds = new Array();
  65783. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65784. var loadedSkeletonsIds = [];
  65785. var loadedMaterialsIds = [];
  65786. var index;
  65787. var cache;
  65788. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65789. var parsedMesh = parsedData.meshes[index];
  65790. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  65791. if (meshesNames !== null) {
  65792. // Remove found mesh name from list.
  65793. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  65794. }
  65795. //Geometry?
  65796. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  65797. //does the file contain geometries?
  65798. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  65799. //find the correct geometry and add it to the scene
  65800. var found = false;
  65801. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  65802. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  65803. return;
  65804. }
  65805. else {
  65806. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  65807. if (parsedGeometryData.id === parsedMesh.geometryId) {
  65808. switch (geometryType) {
  65809. case "boxes":
  65810. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  65811. break;
  65812. case "spheres":
  65813. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  65814. break;
  65815. case "cylinders":
  65816. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  65817. break;
  65818. case "toruses":
  65819. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  65820. break;
  65821. case "grounds":
  65822. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  65823. break;
  65824. case "planes":
  65825. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  65826. break;
  65827. case "torusKnots":
  65828. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  65829. break;
  65830. case "vertexData":
  65831. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  65832. break;
  65833. }
  65834. found = true;
  65835. }
  65836. });
  65837. }
  65838. });
  65839. if (found === false) {
  65840. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  65841. }
  65842. }
  65843. }
  65844. // Material ?
  65845. if (parsedMesh.materialId) {
  65846. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  65847. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65848. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  65849. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  65850. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  65851. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  65852. var subMatId = parsedMultiMaterial.materials[matIndex];
  65853. loadedMaterialsIds.push(subMatId);
  65854. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  65855. if (mat) {
  65856. log += "\n\tMaterial " + mat.toString(fullDetails);
  65857. }
  65858. }
  65859. loadedMaterialsIds.push(parsedMultiMaterial.id);
  65860. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65861. if (mmat) {
  65862. materialFound = true;
  65863. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  65864. }
  65865. break;
  65866. }
  65867. }
  65868. }
  65869. if (materialFound === false) {
  65870. loadedMaterialsIds.push(parsedMesh.materialId);
  65871. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  65872. if (!mat) {
  65873. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  65874. }
  65875. else {
  65876. log += "\n\tMaterial " + mat.toString(fullDetails);
  65877. }
  65878. }
  65879. }
  65880. // Skeleton ?
  65881. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65882. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  65883. if (skeletonAlreadyLoaded === false) {
  65884. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  65885. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  65886. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  65887. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65888. skeletons.push(skeleton);
  65889. loadedSkeletonsIds.push(parsedSkeleton.id);
  65890. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  65891. }
  65892. }
  65893. }
  65894. }
  65895. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65896. meshes.push(mesh);
  65897. log += "\n\tMesh " + mesh.toString(fullDetails);
  65898. }
  65899. }
  65900. // Connecting parents
  65901. var currentMesh;
  65902. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65903. currentMesh = scene.meshes[index];
  65904. if (currentMesh._waitingParentId) {
  65905. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  65906. currentMesh._waitingParentId = null;
  65907. }
  65908. }
  65909. // freeze and compute world matrix application
  65910. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65911. currentMesh = scene.meshes[index];
  65912. if (currentMesh._waitingFreezeWorldMatrix) {
  65913. currentMesh.freezeWorldMatrix();
  65914. currentMesh._waitingFreezeWorldMatrix = null;
  65915. }
  65916. else {
  65917. currentMesh.computeWorldMatrix(true);
  65918. }
  65919. }
  65920. }
  65921. // Particles
  65922. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  65923. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  65924. var parsedParticleSystem = parsedData.particleSystems[index];
  65925. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  65926. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  65927. }
  65928. }
  65929. }
  65930. return true;
  65931. }
  65932. catch (err) {
  65933. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  65934. if (onError) {
  65935. onError(msg, err);
  65936. }
  65937. else {
  65938. BABYLON.Tools.Log(msg);
  65939. throw err;
  65940. }
  65941. }
  65942. finally {
  65943. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65944. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65945. }
  65946. }
  65947. return false;
  65948. },
  65949. load: function (scene, data, rootUrl, onError) {
  65950. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65951. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65952. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65953. // and avoid problems with multiple concurrent .babylon loads.
  65954. var log = "importScene has failed JSON parse";
  65955. try {
  65956. var parsedData = JSON.parse(data);
  65957. log = "";
  65958. // Scene
  65959. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  65960. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  65961. }
  65962. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  65963. scene.autoClear = parsedData.autoClear;
  65964. }
  65965. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  65966. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  65967. }
  65968. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  65969. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  65970. }
  65971. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  65972. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  65973. }
  65974. // Fog
  65975. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  65976. scene.fogMode = parsedData.fogMode;
  65977. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  65978. scene.fogStart = parsedData.fogStart;
  65979. scene.fogEnd = parsedData.fogEnd;
  65980. scene.fogDensity = parsedData.fogDensity;
  65981. log += "\tFog mode for scene: ";
  65982. switch (scene.fogMode) {
  65983. // getters not compiling, so using hardcoded
  65984. case 1:
  65985. log += "exp\n";
  65986. break;
  65987. case 2:
  65988. log += "exp2\n";
  65989. break;
  65990. case 3:
  65991. log += "linear\n";
  65992. break;
  65993. }
  65994. }
  65995. //Physics
  65996. if (parsedData.physicsEnabled) {
  65997. var physicsPlugin;
  65998. if (parsedData.physicsEngine === "cannon") {
  65999. physicsPlugin = new BABYLON.CannonJSPlugin();
  66000. }
  66001. else if (parsedData.physicsEngine === "oimo") {
  66002. physicsPlugin = new BABYLON.OimoJSPlugin();
  66003. }
  66004. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66005. //else - default engine, which is currently oimo
  66006. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66007. scene.enablePhysics(physicsGravity, physicsPlugin);
  66008. }
  66009. // Metadata
  66010. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66011. scene.metadata = parsedData.metadata;
  66012. }
  66013. //collisions, if defined. otherwise, default is true
  66014. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66015. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66016. }
  66017. scene.workerCollisions = !!parsedData.workerCollisions;
  66018. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66019. if (!container) {
  66020. return false;
  66021. }
  66022. if (parsedData.autoAnimate) {
  66023. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66024. }
  66025. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66026. scene.setActiveCameraByID(parsedData.activeCameraID);
  66027. }
  66028. // Environment texture
  66029. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66030. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  66031. if (parsedData.createDefaultSkybox === true) {
  66032. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  66033. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  66034. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  66035. }
  66036. }
  66037. // Finish
  66038. return true;
  66039. }
  66040. catch (err) {
  66041. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  66042. if (onError) {
  66043. onError(msg, err);
  66044. }
  66045. else {
  66046. BABYLON.Tools.Log(msg);
  66047. throw err;
  66048. }
  66049. }
  66050. finally {
  66051. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66052. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66053. }
  66054. }
  66055. return false;
  66056. },
  66057. loadAssetContainer: function (scene, data, rootUrl, onError) {
  66058. var container = loadAssetContainer(scene, data, rootUrl, onError);
  66059. return container;
  66060. }
  66061. });
  66062. })(BABYLON || (BABYLON = {}));
  66063. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  66064. "use strict";
  66065. var BABYLON;
  66066. (function (BABYLON) {
  66067. var FilesInput = /** @class */ (function () {
  66068. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  66069. this.onProcessFileCallback = function () { return true; };
  66070. this._engine = engine;
  66071. this._currentScene = scene;
  66072. this._sceneLoadedCallback = sceneLoadedCallback;
  66073. this._progressCallback = progressCallback;
  66074. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  66075. this._textureLoadingCallback = textureLoadingCallback;
  66076. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  66077. this._onReloadCallback = onReloadCallback;
  66078. this._errorCallback = errorCallback;
  66079. }
  66080. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66081. var _this = this;
  66082. if (elementToMonitor) {
  66083. this._elementToMonitor = elementToMonitor;
  66084. this._dragEnterHandler = function (e) { _this.drag(e); };
  66085. this._dragOverHandler = function (e) { _this.drag(e); };
  66086. this._dropHandler = function (e) { _this.drop(e); };
  66087. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  66088. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  66089. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  66090. }
  66091. };
  66092. FilesInput.prototype.dispose = function () {
  66093. if (!this._elementToMonitor) {
  66094. return;
  66095. }
  66096. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  66097. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  66098. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  66099. };
  66100. FilesInput.prototype.renderFunction = function () {
  66101. if (this._additionalRenderLoopLogicCallback) {
  66102. this._additionalRenderLoopLogicCallback();
  66103. }
  66104. if (this._currentScene) {
  66105. if (this._textureLoadingCallback) {
  66106. var remaining = this._currentScene.getWaitingItemsCount();
  66107. if (remaining > 0) {
  66108. this._textureLoadingCallback(remaining);
  66109. }
  66110. }
  66111. this._currentScene.render();
  66112. }
  66113. };
  66114. FilesInput.prototype.drag = function (e) {
  66115. e.stopPropagation();
  66116. e.preventDefault();
  66117. };
  66118. FilesInput.prototype.drop = function (eventDrop) {
  66119. eventDrop.stopPropagation();
  66120. eventDrop.preventDefault();
  66121. this.loadFiles(eventDrop);
  66122. };
  66123. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66124. var _this = this;
  66125. var reader = folder.createReader();
  66126. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66127. reader.readEntries(function (entries) {
  66128. remaining.count += entries.length;
  66129. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66130. var entry = entries_1[_i];
  66131. if (entry.isFile) {
  66132. entry.file(function (file) {
  66133. file.correctName = relativePath + file.name;
  66134. files.push(file);
  66135. if (--remaining.count === 0) {
  66136. callback();
  66137. }
  66138. });
  66139. }
  66140. else if (entry.isDirectory) {
  66141. _this._traverseFolder(entry, files, remaining, callback);
  66142. }
  66143. }
  66144. if (--remaining.count) {
  66145. callback();
  66146. }
  66147. });
  66148. };
  66149. FilesInput.prototype._processFiles = function (files) {
  66150. for (var i = 0; i < files.length; i++) {
  66151. var name = files[i].correctName.toLowerCase();
  66152. var extension = name.split('.').pop();
  66153. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66154. continue;
  66155. }
  66156. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66157. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66158. this._sceneFileToLoad = files[i];
  66159. }
  66160. else {
  66161. FilesInput.FilesToLoad[name] = files[i];
  66162. }
  66163. }
  66164. };
  66165. FilesInput.prototype.loadFiles = function (event) {
  66166. var _this = this;
  66167. if (this._startingProcessingFilesCallback)
  66168. this._startingProcessingFilesCallback();
  66169. // Handling data transfer via drag'n'drop
  66170. if (event && event.dataTransfer && event.dataTransfer.files) {
  66171. this._filesToLoad = event.dataTransfer.files;
  66172. }
  66173. // Handling files from input files
  66174. if (event && event.target && event.target.files) {
  66175. this._filesToLoad = event.target.files;
  66176. }
  66177. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66178. var files_1 = new Array();
  66179. var folders = [];
  66180. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66181. for (var i = 0; i < this._filesToLoad.length; i++) {
  66182. var fileToLoad = this._filesToLoad[i];
  66183. var name_1 = fileToLoad.name.toLowerCase();
  66184. var entry = void 0;
  66185. fileToLoad.correctName = name_1;
  66186. if (items) {
  66187. var item = items[i];
  66188. if (item.getAsEntry) {
  66189. entry = item.getAsEntry();
  66190. }
  66191. else if (item.webkitGetAsEntry) {
  66192. entry = item.webkitGetAsEntry();
  66193. }
  66194. }
  66195. if (!entry) {
  66196. files_1.push(fileToLoad);
  66197. }
  66198. else {
  66199. if (entry.isDirectory) {
  66200. folders.push(entry);
  66201. }
  66202. else {
  66203. files_1.push(fileToLoad);
  66204. }
  66205. }
  66206. }
  66207. if (folders.length === 0) {
  66208. this._processFiles(files_1);
  66209. this._processReload();
  66210. }
  66211. else {
  66212. var remaining = { count: folders.length };
  66213. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66214. var folder = folders_1[_i];
  66215. this._traverseFolder(folder, files_1, remaining, function () {
  66216. _this._processFiles(files_1);
  66217. if (remaining.count === 0) {
  66218. _this._processReload();
  66219. }
  66220. });
  66221. }
  66222. }
  66223. }
  66224. };
  66225. FilesInput.prototype._processReload = function () {
  66226. if (this._onReloadCallback) {
  66227. this._onReloadCallback(this._sceneFileToLoad);
  66228. }
  66229. else {
  66230. this.reload();
  66231. }
  66232. };
  66233. FilesInput.prototype.reload = function () {
  66234. var _this = this;
  66235. // If a scene file has been provided
  66236. if (this._sceneFileToLoad) {
  66237. if (this._currentScene) {
  66238. if (BABYLON.Tools.errorsCount > 0) {
  66239. BABYLON.Tools.ClearLogCache();
  66240. }
  66241. this._engine.stopRenderLoop();
  66242. this._currentScene.dispose();
  66243. }
  66244. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  66245. if (_this._progressCallback) {
  66246. _this._progressCallback(progress);
  66247. }
  66248. }).then(function (scene) {
  66249. _this._currentScene = scene;
  66250. if (_this._sceneLoadedCallback) {
  66251. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  66252. }
  66253. // Wait for textures and shaders to be ready
  66254. _this._currentScene.executeWhenReady(function () {
  66255. _this._engine.runRenderLoop(function () {
  66256. _this.renderFunction();
  66257. });
  66258. });
  66259. }).catch(function (error) {
  66260. if (_this._errorCallback) {
  66261. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  66262. }
  66263. });
  66264. }
  66265. else {
  66266. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  66267. }
  66268. };
  66269. FilesInput.FilesToLoad = {};
  66270. return FilesInput;
  66271. }());
  66272. BABYLON.FilesInput = FilesInput;
  66273. })(BABYLON || (BABYLON = {}));
  66274. //# sourceMappingURL=babylon.filesInput.js.map
  66275. "use strict";
  66276. var BABYLON;
  66277. (function (BABYLON) {
  66278. /**
  66279. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66280. * The underlying implementation relies on an associative array to ensure the best performances.
  66281. * The value can be anything including 'null' but except 'undefined'
  66282. */
  66283. var StringDictionary = /** @class */ (function () {
  66284. function StringDictionary() {
  66285. this._count = 0;
  66286. this._data = {};
  66287. }
  66288. /**
  66289. * This will clear this dictionary and copy the content from the 'source' one.
  66290. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66291. * @param source the dictionary to take the content from and copy to this dictionary
  66292. */
  66293. StringDictionary.prototype.copyFrom = function (source) {
  66294. var _this = this;
  66295. this.clear();
  66296. source.forEach(function (t, v) { return _this.add(t, v); });
  66297. };
  66298. /**
  66299. * Get a value based from its key
  66300. * @param key the given key to get the matching value from
  66301. * @return the value if found, otherwise undefined is returned
  66302. */
  66303. StringDictionary.prototype.get = function (key) {
  66304. var val = this._data[key];
  66305. if (val !== undefined) {
  66306. return val;
  66307. }
  66308. return undefined;
  66309. };
  66310. /**
  66311. * Get a value from its key or add it if it doesn't exist.
  66312. * This method will ensure you that a given key/data will be present in the dictionary.
  66313. * @param key the given key to get the matching value from
  66314. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66315. * The factory will only be invoked if there's no data for the given key.
  66316. * @return the value corresponding to the key.
  66317. */
  66318. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  66319. var val = this.get(key);
  66320. if (val !== undefined) {
  66321. return val;
  66322. }
  66323. val = factory(key);
  66324. if (val) {
  66325. this.add(key, val);
  66326. }
  66327. return val;
  66328. };
  66329. /**
  66330. * Get a value from its key if present in the dictionary otherwise add it
  66331. * @param key the key to get the value from
  66332. * @param val if there's no such key/value pair in the dictionary add it with this value
  66333. * @return the value corresponding to the key
  66334. */
  66335. StringDictionary.prototype.getOrAdd = function (key, val) {
  66336. var curVal = this.get(key);
  66337. if (curVal !== undefined) {
  66338. return curVal;
  66339. }
  66340. this.add(key, val);
  66341. return val;
  66342. };
  66343. /**
  66344. * Check if there's a given key in the dictionary
  66345. * @param key the key to check for
  66346. * @return true if the key is present, false otherwise
  66347. */
  66348. StringDictionary.prototype.contains = function (key) {
  66349. return this._data[key] !== undefined;
  66350. };
  66351. /**
  66352. * Add a new key and its corresponding value
  66353. * @param key the key to add
  66354. * @param value the value corresponding to the key
  66355. * @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
  66356. */
  66357. StringDictionary.prototype.add = function (key, value) {
  66358. if (this._data[key] !== undefined) {
  66359. return false;
  66360. }
  66361. this._data[key] = value;
  66362. ++this._count;
  66363. return true;
  66364. };
  66365. StringDictionary.prototype.set = function (key, value) {
  66366. if (this._data[key] === undefined) {
  66367. return false;
  66368. }
  66369. this._data[key] = value;
  66370. return true;
  66371. };
  66372. /**
  66373. * Get the element of the given key and remove it from the dictionary
  66374. * @param key
  66375. */
  66376. StringDictionary.prototype.getAndRemove = function (key) {
  66377. var val = this.get(key);
  66378. if (val !== undefined) {
  66379. delete this._data[key];
  66380. --this._count;
  66381. return val;
  66382. }
  66383. return null;
  66384. };
  66385. /**
  66386. * Remove a key/value from the dictionary.
  66387. * @param key the key to remove
  66388. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  66389. */
  66390. StringDictionary.prototype.remove = function (key) {
  66391. if (this.contains(key)) {
  66392. delete this._data[key];
  66393. --this._count;
  66394. return true;
  66395. }
  66396. return false;
  66397. };
  66398. /**
  66399. * Clear the whole content of the dictionary
  66400. */
  66401. StringDictionary.prototype.clear = function () {
  66402. this._data = {};
  66403. this._count = 0;
  66404. };
  66405. Object.defineProperty(StringDictionary.prototype, "count", {
  66406. get: function () {
  66407. return this._count;
  66408. },
  66409. enumerable: true,
  66410. configurable: true
  66411. });
  66412. /**
  66413. * Execute a callback on each key/val of the dictionary.
  66414. * Note that you can remove any element in this dictionary in the callback implementation
  66415. * @param callback the callback to execute on a given key/value pair
  66416. */
  66417. StringDictionary.prototype.forEach = function (callback) {
  66418. for (var cur in this._data) {
  66419. var val = this._data[cur];
  66420. callback(cur, val);
  66421. }
  66422. };
  66423. /**
  66424. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  66425. * If the callback returns null or undefined the method will iterate to the next key/value pair
  66426. * Note that you can remove any element in this dictionary in the callback implementation
  66427. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  66428. */
  66429. StringDictionary.prototype.first = function (callback) {
  66430. for (var cur in this._data) {
  66431. var val = this._data[cur];
  66432. var res = callback(cur, val);
  66433. if (res) {
  66434. return res;
  66435. }
  66436. }
  66437. return null;
  66438. };
  66439. return StringDictionary;
  66440. }());
  66441. BABYLON.StringDictionary = StringDictionary;
  66442. })(BABYLON || (BABYLON = {}));
  66443. //# sourceMappingURL=babylon.stringDictionary.js.map
  66444. "use strict";
  66445. var BABYLON;
  66446. (function (BABYLON) {
  66447. var Tags = /** @class */ (function () {
  66448. function Tags() {
  66449. }
  66450. Tags.EnableFor = function (obj) {
  66451. obj._tags = obj._tags || {};
  66452. obj.hasTags = function () {
  66453. return Tags.HasTags(obj);
  66454. };
  66455. obj.addTags = function (tagsString) {
  66456. return Tags.AddTagsTo(obj, tagsString);
  66457. };
  66458. obj.removeTags = function (tagsString) {
  66459. return Tags.RemoveTagsFrom(obj, tagsString);
  66460. };
  66461. obj.matchesTagsQuery = function (tagsQuery) {
  66462. return Tags.MatchesQuery(obj, tagsQuery);
  66463. };
  66464. };
  66465. Tags.DisableFor = function (obj) {
  66466. delete obj._tags;
  66467. delete obj.hasTags;
  66468. delete obj.addTags;
  66469. delete obj.removeTags;
  66470. delete obj.matchesTagsQuery;
  66471. };
  66472. Tags.HasTags = function (obj) {
  66473. if (!obj._tags) {
  66474. return false;
  66475. }
  66476. return !BABYLON.Tools.IsEmpty(obj._tags);
  66477. };
  66478. Tags.GetTags = function (obj, asString) {
  66479. if (asString === void 0) { asString = true; }
  66480. if (!obj._tags) {
  66481. return null;
  66482. }
  66483. if (asString) {
  66484. var tagsArray = [];
  66485. for (var tag in obj._tags) {
  66486. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  66487. tagsArray.push(tag);
  66488. }
  66489. }
  66490. return tagsArray.join(" ");
  66491. }
  66492. else {
  66493. return obj._tags;
  66494. }
  66495. };
  66496. // the tags 'true' and 'false' are reserved and cannot be used as tags
  66497. // a tag cannot start with '||', '&&', and '!'
  66498. // it cannot contain whitespaces
  66499. Tags.AddTagsTo = function (obj, tagsString) {
  66500. if (!tagsString) {
  66501. return;
  66502. }
  66503. if (typeof tagsString !== "string") {
  66504. return;
  66505. }
  66506. var tags = tagsString.split(" ");
  66507. tags.forEach(function (tag, index, array) {
  66508. Tags._AddTagTo(obj, tag);
  66509. });
  66510. };
  66511. Tags._AddTagTo = function (obj, tag) {
  66512. tag = tag.trim();
  66513. if (tag === "" || tag === "true" || tag === "false") {
  66514. return;
  66515. }
  66516. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  66517. return;
  66518. }
  66519. Tags.EnableFor(obj);
  66520. obj._tags[tag] = true;
  66521. };
  66522. Tags.RemoveTagsFrom = function (obj, tagsString) {
  66523. if (!Tags.HasTags(obj)) {
  66524. return;
  66525. }
  66526. var tags = tagsString.split(" ");
  66527. for (var t in tags) {
  66528. Tags._RemoveTagFrom(obj, tags[t]);
  66529. }
  66530. };
  66531. Tags._RemoveTagFrom = function (obj, tag) {
  66532. delete obj._tags[tag];
  66533. };
  66534. Tags.MatchesQuery = function (obj, tagsQuery) {
  66535. if (tagsQuery === undefined) {
  66536. return true;
  66537. }
  66538. if (tagsQuery === "") {
  66539. return Tags.HasTags(obj);
  66540. }
  66541. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  66542. };
  66543. return Tags;
  66544. }());
  66545. BABYLON.Tags = Tags;
  66546. })(BABYLON || (BABYLON = {}));
  66547. //# sourceMappingURL=babylon.tags.js.map
  66548. "use strict";
  66549. var BABYLON;
  66550. (function (BABYLON) {
  66551. var AndOrNotEvaluator = /** @class */ (function () {
  66552. function AndOrNotEvaluator() {
  66553. }
  66554. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  66555. if (!query.match(/\([^\(\)]*\)/g)) {
  66556. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  66557. }
  66558. else {
  66559. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  66560. // remove parenthesis
  66561. r = r.slice(1, r.length - 1);
  66562. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  66563. });
  66564. }
  66565. if (query === "true") {
  66566. return true;
  66567. }
  66568. if (query === "false") {
  66569. return false;
  66570. }
  66571. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  66572. };
  66573. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  66574. evaluateCallback = evaluateCallback || (function (r) {
  66575. return r === "true" ? true : false;
  66576. });
  66577. var result;
  66578. var or = parenthesisContent.split("||");
  66579. for (var i in or) {
  66580. if (or.hasOwnProperty(i)) {
  66581. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  66582. var and = ori.split("&&");
  66583. if (and.length > 1) {
  66584. for (var j = 0; j < and.length; ++j) {
  66585. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  66586. if (andj !== "true" && andj !== "false") {
  66587. if (andj[0] === "!") {
  66588. result = !evaluateCallback(andj.substring(1));
  66589. }
  66590. else {
  66591. result = evaluateCallback(andj);
  66592. }
  66593. }
  66594. else {
  66595. result = andj === "true" ? true : false;
  66596. }
  66597. if (!result) {
  66598. ori = "false";
  66599. break;
  66600. }
  66601. }
  66602. }
  66603. if (result || ori === "true") {
  66604. result = true;
  66605. break;
  66606. }
  66607. // result equals false (or undefined)
  66608. if (ori !== "true" && ori !== "false") {
  66609. if (ori[0] === "!") {
  66610. result = !evaluateCallback(ori.substring(1));
  66611. }
  66612. else {
  66613. result = evaluateCallback(ori);
  66614. }
  66615. }
  66616. else {
  66617. result = ori === "true" ? true : false;
  66618. }
  66619. }
  66620. }
  66621. // the whole parenthesis scope is replaced by 'true' or 'false'
  66622. return result ? "true" : "false";
  66623. };
  66624. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  66625. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  66626. // remove whitespaces
  66627. r = r.replace(/[\s]/g, function () { return ""; });
  66628. return r.length % 2 ? "!" : "";
  66629. });
  66630. booleanString = booleanString.trim();
  66631. if (booleanString === "!true") {
  66632. booleanString = "false";
  66633. }
  66634. else if (booleanString === "!false") {
  66635. booleanString = "true";
  66636. }
  66637. return booleanString;
  66638. };
  66639. return AndOrNotEvaluator;
  66640. }());
  66641. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  66642. })(BABYLON || (BABYLON = {}));
  66643. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  66644. "use strict";
  66645. var BABYLON;
  66646. (function (BABYLON) {
  66647. var Database = /** @class */ (function () {
  66648. function Database(urlToScene, callbackManifestChecked) {
  66649. // Handling various flavors of prefixed version of IndexedDB
  66650. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  66651. this.callbackManifestChecked = callbackManifestChecked;
  66652. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  66653. this.db = null;
  66654. this._enableSceneOffline = false;
  66655. this._enableTexturesOffline = false;
  66656. this.manifestVersionFound = 0;
  66657. this.mustUpdateRessources = false;
  66658. this.hasReachedQuota = false;
  66659. if (!Database.IDBStorageEnabled) {
  66660. this.callbackManifestChecked(true);
  66661. }
  66662. else {
  66663. this.checkManifestFile();
  66664. }
  66665. }
  66666. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  66667. get: function () {
  66668. return this._enableSceneOffline;
  66669. },
  66670. enumerable: true,
  66671. configurable: true
  66672. });
  66673. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  66674. get: function () {
  66675. return this._enableTexturesOffline;
  66676. },
  66677. enumerable: true,
  66678. configurable: true
  66679. });
  66680. Database.prototype.checkManifestFile = function () {
  66681. var _this = this;
  66682. var noManifestFile = function () {
  66683. _this._enableSceneOffline = false;
  66684. _this._enableTexturesOffline = false;
  66685. _this.callbackManifestChecked(false);
  66686. };
  66687. var timeStampUsed = false;
  66688. var manifestURL = this.currentSceneUrl + ".manifest";
  66689. var xhr = new XMLHttpRequest();
  66690. if (navigator.onLine) {
  66691. // Adding a timestamp to by-pass browsers' cache
  66692. timeStampUsed = true;
  66693. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  66694. }
  66695. xhr.open("GET", manifestURL, true);
  66696. xhr.addEventListener("load", function () {
  66697. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  66698. try {
  66699. var manifestFile = JSON.parse(xhr.response);
  66700. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  66701. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  66702. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  66703. _this.manifestVersionFound = manifestFile.version;
  66704. }
  66705. if (_this.callbackManifestChecked) {
  66706. _this.callbackManifestChecked(true);
  66707. }
  66708. }
  66709. catch (ex) {
  66710. noManifestFile();
  66711. }
  66712. }
  66713. else {
  66714. noManifestFile();
  66715. }
  66716. }, false);
  66717. xhr.addEventListener("error", function (event) {
  66718. if (timeStampUsed) {
  66719. timeStampUsed = false;
  66720. // Let's retry without the timeStamp
  66721. // It could fail when coupled with HTML5 Offline API
  66722. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  66723. xhr.open("GET", retryManifestURL, true);
  66724. xhr.send();
  66725. }
  66726. else {
  66727. noManifestFile();
  66728. }
  66729. }, false);
  66730. try {
  66731. xhr.send();
  66732. }
  66733. catch (ex) {
  66734. BABYLON.Tools.Error("Error on XHR send request.");
  66735. this.callbackManifestChecked(false);
  66736. }
  66737. };
  66738. Database.prototype.openAsync = function (successCallback, errorCallback) {
  66739. var _this = this;
  66740. var handleError = function () {
  66741. _this.isSupported = false;
  66742. if (errorCallback)
  66743. errorCallback();
  66744. };
  66745. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  66746. // Your browser doesn't support IndexedDB
  66747. this.isSupported = false;
  66748. if (errorCallback)
  66749. errorCallback();
  66750. }
  66751. else {
  66752. // If the DB hasn't been opened or created yet
  66753. if (!this.db) {
  66754. this.hasReachedQuota = false;
  66755. this.isSupported = true;
  66756. var request = this.idbFactory.open("babylonjs", 1);
  66757. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  66758. request.onerror = function (event) {
  66759. handleError();
  66760. };
  66761. // executes when a version change transaction cannot complete due to other active transactions
  66762. request.onblocked = function (event) {
  66763. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  66764. handleError();
  66765. };
  66766. // DB has been opened successfully
  66767. request.onsuccess = function (event) {
  66768. _this.db = request.result;
  66769. successCallback();
  66770. };
  66771. // Initialization of the DB. Creating Scenes & Textures stores
  66772. request.onupgradeneeded = function (event) {
  66773. _this.db = (event.target).result;
  66774. if (_this.db) {
  66775. try {
  66776. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  66777. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  66778. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  66779. }
  66780. catch (ex) {
  66781. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  66782. handleError();
  66783. }
  66784. }
  66785. };
  66786. }
  66787. else {
  66788. if (successCallback)
  66789. successCallback();
  66790. }
  66791. }
  66792. };
  66793. Database.prototype.loadImageFromDB = function (url, image) {
  66794. var _this = this;
  66795. var completeURL = Database.ReturnFullUrlLocation(url);
  66796. var saveAndLoadImage = function () {
  66797. if (!_this.hasReachedQuota && _this.db !== null) {
  66798. // the texture is not yet in the DB, let's try to save it
  66799. _this._saveImageIntoDBAsync(completeURL, image);
  66800. }
  66801. else {
  66802. image.src = url;
  66803. }
  66804. };
  66805. if (!this.mustUpdateRessources) {
  66806. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  66807. }
  66808. else {
  66809. saveAndLoadImage();
  66810. }
  66811. };
  66812. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  66813. if (this.isSupported && this.db !== null) {
  66814. var texture;
  66815. var transaction = this.db.transaction(["textures"]);
  66816. transaction.onabort = function (event) {
  66817. image.src = url;
  66818. };
  66819. transaction.oncomplete = function (event) {
  66820. var blobTextureURL;
  66821. if (texture) {
  66822. var URL = window.URL || window.webkitURL;
  66823. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  66824. image.onerror = function () {
  66825. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  66826. image.src = url;
  66827. };
  66828. image.src = blobTextureURL;
  66829. }
  66830. else {
  66831. notInDBCallback();
  66832. }
  66833. };
  66834. var getRequest = transaction.objectStore("textures").get(url);
  66835. getRequest.onsuccess = function (event) {
  66836. texture = (event.target).result;
  66837. };
  66838. getRequest.onerror = function (event) {
  66839. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  66840. image.src = url;
  66841. };
  66842. }
  66843. else {
  66844. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66845. image.src = url;
  66846. }
  66847. };
  66848. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  66849. var _this = this;
  66850. if (this.isSupported) {
  66851. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  66852. var generateBlobUrl = function () {
  66853. var blobTextureURL;
  66854. if (blob) {
  66855. var URL = window.URL || window.webkitURL;
  66856. try {
  66857. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  66858. }
  66859. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  66860. catch (ex) {
  66861. blobTextureURL = URL.createObjectURL(blob);
  66862. }
  66863. }
  66864. if (blobTextureURL) {
  66865. image.src = blobTextureURL;
  66866. }
  66867. };
  66868. if (Database.IsUASupportingBlobStorage) {
  66869. var xhr = new XMLHttpRequest(), blob;
  66870. xhr.open("GET", url, true);
  66871. xhr.responseType = "blob";
  66872. xhr.addEventListener("load", function () {
  66873. if (xhr.status === 200 && _this.db) {
  66874. // Blob as response (XHR2)
  66875. blob = xhr.response;
  66876. var transaction = _this.db.transaction(["textures"], "readwrite");
  66877. // the transaction could abort because of a QuotaExceededError error
  66878. transaction.onabort = function (event) {
  66879. try {
  66880. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  66881. var srcElement = (event.srcElement || event.target);
  66882. var error = srcElement.error;
  66883. if (error && error.name === "QuotaExceededError") {
  66884. _this.hasReachedQuota = true;
  66885. }
  66886. }
  66887. catch (ex) { }
  66888. generateBlobUrl();
  66889. };
  66890. transaction.oncomplete = function (event) {
  66891. generateBlobUrl();
  66892. };
  66893. var newTexture = { textureUrl: url, data: blob };
  66894. try {
  66895. // Put the blob into the dabase
  66896. var addRequest = transaction.objectStore("textures").put(newTexture);
  66897. addRequest.onsuccess = function (event) {
  66898. };
  66899. addRequest.onerror = function (event) {
  66900. generateBlobUrl();
  66901. };
  66902. }
  66903. catch (ex) {
  66904. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  66905. if (ex.code === 25) {
  66906. Database.IsUASupportingBlobStorage = false;
  66907. }
  66908. image.src = url;
  66909. }
  66910. }
  66911. else {
  66912. image.src = url;
  66913. }
  66914. }, false);
  66915. xhr.addEventListener("error", function (event) {
  66916. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  66917. image.src = url;
  66918. }, false);
  66919. xhr.send();
  66920. }
  66921. else {
  66922. image.src = url;
  66923. }
  66924. }
  66925. else {
  66926. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66927. image.src = url;
  66928. }
  66929. };
  66930. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  66931. var _this = this;
  66932. var updateVersion = function () {
  66933. // the version is not yet in the DB or we need to update it
  66934. _this._saveVersionIntoDBAsync(url, versionLoaded);
  66935. };
  66936. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  66937. };
  66938. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  66939. var _this = this;
  66940. if (this.isSupported && this.db) {
  66941. var version;
  66942. try {
  66943. var transaction = this.db.transaction(["versions"]);
  66944. transaction.oncomplete = function (event) {
  66945. if (version) {
  66946. // If the version in the JSON file is > than the version in DB
  66947. if (_this.manifestVersionFound > version.data) {
  66948. _this.mustUpdateRessources = true;
  66949. updateInDBCallback();
  66950. }
  66951. else {
  66952. callback(version.data);
  66953. }
  66954. }
  66955. else {
  66956. _this.mustUpdateRessources = true;
  66957. updateInDBCallback();
  66958. }
  66959. };
  66960. transaction.onabort = function (event) {
  66961. callback(-1);
  66962. };
  66963. var getRequest = transaction.objectStore("versions").get(url);
  66964. getRequest.onsuccess = function (event) {
  66965. version = (event.target).result;
  66966. };
  66967. getRequest.onerror = function (event) {
  66968. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  66969. callback(-1);
  66970. };
  66971. }
  66972. catch (ex) {
  66973. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  66974. callback(-1);
  66975. }
  66976. }
  66977. else {
  66978. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66979. callback(-1);
  66980. }
  66981. };
  66982. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  66983. var _this = this;
  66984. if (this.isSupported && !this.hasReachedQuota && this.db) {
  66985. try {
  66986. // Open a transaction to the database
  66987. var transaction = this.db.transaction(["versions"], "readwrite");
  66988. // the transaction could abort because of a QuotaExceededError error
  66989. transaction.onabort = function (event) {
  66990. try {
  66991. var error = event.srcElement['error'];
  66992. if (error && error.name === "QuotaExceededError") {
  66993. _this.hasReachedQuota = true;
  66994. }
  66995. }
  66996. catch (ex) { }
  66997. callback(-1);
  66998. };
  66999. transaction.oncomplete = function (event) {
  67000. callback(_this.manifestVersionFound);
  67001. };
  67002. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67003. // Put the scene into the database
  67004. var addRequest = transaction.objectStore("versions").put(newVersion);
  67005. addRequest.onsuccess = function (event) {
  67006. };
  67007. addRequest.onerror = function (event) {
  67008. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67009. };
  67010. }
  67011. catch (ex) {
  67012. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67013. callback(-1);
  67014. }
  67015. }
  67016. else {
  67017. callback(-1);
  67018. }
  67019. };
  67020. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67021. var _this = this;
  67022. var completeUrl = Database.ReturnFullUrlLocation(url);
  67023. var saveAndLoadFile = function () {
  67024. // the scene is not yet in the DB, let's try to save it
  67025. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67026. };
  67027. this._checkVersionFromDB(completeUrl, function (version) {
  67028. if (version !== -1) {
  67029. if (!_this.mustUpdateRessources) {
  67030. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  67031. }
  67032. else {
  67033. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  67034. }
  67035. }
  67036. else {
  67037. if (errorCallback) {
  67038. errorCallback();
  67039. }
  67040. }
  67041. });
  67042. };
  67043. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  67044. if (this.isSupported && this.db) {
  67045. var targetStore;
  67046. if (url.indexOf(".babylon") !== -1) {
  67047. targetStore = "scenes";
  67048. }
  67049. else {
  67050. targetStore = "textures";
  67051. }
  67052. var file;
  67053. var transaction = this.db.transaction([targetStore]);
  67054. transaction.oncomplete = function (event) {
  67055. if (file) {
  67056. callback(file.data);
  67057. }
  67058. else {
  67059. notInDBCallback();
  67060. }
  67061. };
  67062. transaction.onabort = function (event) {
  67063. notInDBCallback();
  67064. };
  67065. var getRequest = transaction.objectStore(targetStore).get(url);
  67066. getRequest.onsuccess = function (event) {
  67067. file = (event.target).result;
  67068. };
  67069. getRequest.onerror = function (event) {
  67070. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  67071. notInDBCallback();
  67072. };
  67073. }
  67074. else {
  67075. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67076. callback();
  67077. }
  67078. };
  67079. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  67080. var _this = this;
  67081. if (this.isSupported) {
  67082. var targetStore;
  67083. if (url.indexOf(".babylon") !== -1) {
  67084. targetStore = "scenes";
  67085. }
  67086. else {
  67087. targetStore = "textures";
  67088. }
  67089. // Create XHR
  67090. var xhr = new XMLHttpRequest();
  67091. var fileData;
  67092. xhr.open("GET", url, true);
  67093. if (useArrayBuffer) {
  67094. xhr.responseType = "arraybuffer";
  67095. }
  67096. if (progressCallback) {
  67097. xhr.onprogress = progressCallback;
  67098. }
  67099. xhr.addEventListener("load", function () {
  67100. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  67101. // Blob as response (XHR2)
  67102. //fileData = xhr.responseText;
  67103. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  67104. if (!_this.hasReachedQuota && _this.db) {
  67105. // Open a transaction to the database
  67106. var transaction = _this.db.transaction([targetStore], "readwrite");
  67107. // the transaction could abort because of a QuotaExceededError error
  67108. transaction.onabort = function (event) {
  67109. try {
  67110. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67111. var error = event.srcElement['error'];
  67112. if (error && error.name === "QuotaExceededError") {
  67113. _this.hasReachedQuota = true;
  67114. }
  67115. }
  67116. catch (ex) { }
  67117. callback(fileData);
  67118. };
  67119. transaction.oncomplete = function (event) {
  67120. callback(fileData);
  67121. };
  67122. var newFile;
  67123. if (targetStore === "scenes") {
  67124. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67125. }
  67126. else {
  67127. newFile = { textureUrl: url, data: fileData };
  67128. }
  67129. try {
  67130. // Put the scene into the database
  67131. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67132. addRequest.onsuccess = function (event) {
  67133. };
  67134. addRequest.onerror = function (event) {
  67135. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67136. };
  67137. }
  67138. catch (ex) {
  67139. callback(fileData);
  67140. }
  67141. }
  67142. else {
  67143. callback(fileData);
  67144. }
  67145. }
  67146. else {
  67147. callback();
  67148. }
  67149. }, false);
  67150. xhr.addEventListener("error", function (event) {
  67151. BABYLON.Tools.Error("error on XHR request.");
  67152. callback();
  67153. }, false);
  67154. xhr.send();
  67155. }
  67156. else {
  67157. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67158. callback();
  67159. }
  67160. };
  67161. Database.IsUASupportingBlobStorage = true;
  67162. Database.IDBStorageEnabled = true;
  67163. Database.parseURL = function (url) {
  67164. var a = document.createElement('a');
  67165. a.href = url;
  67166. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67167. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67168. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67169. return absLocation;
  67170. };
  67171. Database.ReturnFullUrlLocation = function (url) {
  67172. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67173. return (Database.parseURL(window.location.href) + url);
  67174. }
  67175. else {
  67176. return url;
  67177. }
  67178. };
  67179. return Database;
  67180. }());
  67181. BABYLON.Database = Database;
  67182. })(BABYLON || (BABYLON = {}));
  67183. //# sourceMappingURL=babylon.database.js.map
  67184. "use strict";
  67185. var BABYLON;
  67186. (function (BABYLON) {
  67187. var FresnelParameters = /** @class */ (function () {
  67188. function FresnelParameters() {
  67189. this._isEnabled = true;
  67190. this.leftColor = BABYLON.Color3.White();
  67191. this.rightColor = BABYLON.Color3.Black();
  67192. this.bias = 0;
  67193. this.power = 1;
  67194. }
  67195. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67196. get: function () {
  67197. return this._isEnabled;
  67198. },
  67199. set: function (value) {
  67200. if (this._isEnabled === value) {
  67201. return;
  67202. }
  67203. this._isEnabled = value;
  67204. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67205. },
  67206. enumerable: true,
  67207. configurable: true
  67208. });
  67209. FresnelParameters.prototype.clone = function () {
  67210. var newFresnelParameters = new FresnelParameters();
  67211. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67212. return newFresnelParameters;
  67213. };
  67214. FresnelParameters.prototype.serialize = function () {
  67215. var serializationObject = {};
  67216. serializationObject.isEnabled = this.isEnabled;
  67217. serializationObject.leftColor = this.leftColor.asArray();
  67218. serializationObject.rightColor = this.rightColor.asArray();
  67219. serializationObject.bias = this.bias;
  67220. serializationObject.power = this.power;
  67221. return serializationObject;
  67222. };
  67223. FresnelParameters.Parse = function (parsedFresnelParameters) {
  67224. var fresnelParameters = new FresnelParameters();
  67225. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  67226. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  67227. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  67228. fresnelParameters.bias = parsedFresnelParameters.bias;
  67229. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  67230. return fresnelParameters;
  67231. };
  67232. return FresnelParameters;
  67233. }());
  67234. BABYLON.FresnelParameters = FresnelParameters;
  67235. })(BABYLON || (BABYLON = {}));
  67236. //# sourceMappingURL=babylon.fresnelParameters.js.map
  67237. "use strict";
  67238. var BABYLON;
  67239. (function (BABYLON) {
  67240. var MultiMaterial = /** @class */ (function (_super) {
  67241. __extends(MultiMaterial, _super);
  67242. function MultiMaterial(name, scene) {
  67243. var _this = _super.call(this, name, scene, true) || this;
  67244. scene.multiMaterials.push(_this);
  67245. _this.subMaterials = new Array();
  67246. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  67247. return _this;
  67248. }
  67249. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  67250. get: function () {
  67251. return this._subMaterials;
  67252. },
  67253. set: function (value) {
  67254. this._subMaterials = value;
  67255. this._hookArray(value);
  67256. },
  67257. enumerable: true,
  67258. configurable: true
  67259. });
  67260. MultiMaterial.prototype._hookArray = function (array) {
  67261. var _this = this;
  67262. var oldPush = array.push;
  67263. array.push = function () {
  67264. var items = [];
  67265. for (var _i = 0; _i < arguments.length; _i++) {
  67266. items[_i] = arguments[_i];
  67267. }
  67268. var result = oldPush.apply(array, items);
  67269. _this._markAllSubMeshesAsTexturesDirty();
  67270. return result;
  67271. };
  67272. var oldSplice = array.splice;
  67273. array.splice = function (index, deleteCount) {
  67274. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67275. _this._markAllSubMeshesAsTexturesDirty();
  67276. return deleted;
  67277. };
  67278. };
  67279. // Properties
  67280. MultiMaterial.prototype.getSubMaterial = function (index) {
  67281. if (index < 0 || index >= this.subMaterials.length) {
  67282. return this.getScene().defaultMaterial;
  67283. }
  67284. return this.subMaterials[index];
  67285. };
  67286. MultiMaterial.prototype.getActiveTextures = function () {
  67287. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  67288. if (subMaterial) {
  67289. return subMaterial.getActiveTextures();
  67290. }
  67291. else {
  67292. return [];
  67293. }
  67294. }));
  67295. var _a;
  67296. };
  67297. // Methods
  67298. MultiMaterial.prototype.getClassName = function () {
  67299. return "MultiMaterial";
  67300. };
  67301. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  67302. for (var index = 0; index < this.subMaterials.length; index++) {
  67303. var subMaterial = this.subMaterials[index];
  67304. if (subMaterial) {
  67305. if (subMaterial.storeEffectOnSubMeshes) {
  67306. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  67307. return false;
  67308. }
  67309. continue;
  67310. }
  67311. if (!subMaterial.isReady(mesh)) {
  67312. return false;
  67313. }
  67314. }
  67315. }
  67316. return true;
  67317. };
  67318. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  67319. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  67320. for (var index = 0; index < this.subMaterials.length; index++) {
  67321. var subMaterial = null;
  67322. var current = this.subMaterials[index];
  67323. if (cloneChildren && current) {
  67324. subMaterial = current.clone(name + "-" + current.name);
  67325. }
  67326. else {
  67327. subMaterial = this.subMaterials[index];
  67328. }
  67329. newMultiMaterial.subMaterials.push(subMaterial);
  67330. }
  67331. return newMultiMaterial;
  67332. };
  67333. MultiMaterial.prototype.serialize = function () {
  67334. var serializationObject = {};
  67335. serializationObject.name = this.name;
  67336. serializationObject.id = this.id;
  67337. if (BABYLON.Tags) {
  67338. serializationObject.tags = BABYLON.Tags.GetTags(this);
  67339. }
  67340. serializationObject.materials = [];
  67341. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  67342. var subMat = this.subMaterials[matIndex];
  67343. if (subMat) {
  67344. serializationObject.materials.push(subMat.id);
  67345. }
  67346. else {
  67347. serializationObject.materials.push(null);
  67348. }
  67349. }
  67350. return serializationObject;
  67351. };
  67352. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  67353. var scene = this.getScene();
  67354. if (!scene) {
  67355. return;
  67356. }
  67357. var index = scene.multiMaterials.indexOf(this);
  67358. if (index >= 0) {
  67359. scene.multiMaterials.splice(index, 1);
  67360. }
  67361. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  67362. };
  67363. return MultiMaterial;
  67364. }(BABYLON.Material));
  67365. BABYLON.MultiMaterial = MultiMaterial;
  67366. })(BABYLON || (BABYLON = {}));
  67367. //# sourceMappingURL=babylon.multiMaterial.js.map
  67368. "use strict";
  67369. var BABYLON;
  67370. (function (BABYLON) {
  67371. var FreeCameraTouchInput = /** @class */ (function () {
  67372. function FreeCameraTouchInput() {
  67373. this._offsetX = null;
  67374. this._offsetY = null;
  67375. this._pointerPressed = new Array();
  67376. this.touchAngularSensibility = 200000.0;
  67377. this.touchMoveSensibility = 250.0;
  67378. }
  67379. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  67380. var _this = this;
  67381. var previousPosition = null;
  67382. if (this._pointerInput === undefined) {
  67383. this._onLostFocus = function (evt) {
  67384. _this._offsetX = null;
  67385. _this._offsetY = null;
  67386. };
  67387. this._pointerInput = function (p, s) {
  67388. var evt = p.event;
  67389. if (evt.pointerType === "mouse") {
  67390. return;
  67391. }
  67392. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  67393. if (!noPreventDefault) {
  67394. evt.preventDefault();
  67395. }
  67396. _this._pointerPressed.push(evt.pointerId);
  67397. if (_this._pointerPressed.length !== 1) {
  67398. return;
  67399. }
  67400. previousPosition = {
  67401. x: evt.clientX,
  67402. y: evt.clientY
  67403. };
  67404. }
  67405. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  67406. if (!noPreventDefault) {
  67407. evt.preventDefault();
  67408. }
  67409. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67410. if (index === -1) {
  67411. return;
  67412. }
  67413. _this._pointerPressed.splice(index, 1);
  67414. if (index != 0) {
  67415. return;
  67416. }
  67417. previousPosition = null;
  67418. _this._offsetX = null;
  67419. _this._offsetY = null;
  67420. }
  67421. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  67422. if (!noPreventDefault) {
  67423. evt.preventDefault();
  67424. }
  67425. if (!previousPosition) {
  67426. return;
  67427. }
  67428. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67429. if (index != 0) {
  67430. return;
  67431. }
  67432. _this._offsetX = evt.clientX - previousPosition.x;
  67433. _this._offsetY = -(evt.clientY - previousPosition.y);
  67434. }
  67435. };
  67436. }
  67437. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  67438. if (this._onLostFocus) {
  67439. element.addEventListener("blur", this._onLostFocus);
  67440. }
  67441. };
  67442. FreeCameraTouchInput.prototype.detachControl = function (element) {
  67443. if (this._pointerInput && element) {
  67444. if (this._observer) {
  67445. this.camera.getScene().onPointerObservable.remove(this._observer);
  67446. this._observer = null;
  67447. }
  67448. if (this._onLostFocus) {
  67449. element.removeEventListener("blur", this._onLostFocus);
  67450. this._onLostFocus = null;
  67451. }
  67452. this._pointerPressed = [];
  67453. this._offsetX = null;
  67454. this._offsetY = null;
  67455. }
  67456. };
  67457. FreeCameraTouchInput.prototype.checkInputs = function () {
  67458. if (this._offsetX && this._offsetY) {
  67459. var camera = this.camera;
  67460. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  67461. if (this._pointerPressed.length > 1) {
  67462. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  67463. }
  67464. else {
  67465. var speed = camera._computeLocalCameraSpeed();
  67466. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  67467. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  67468. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  67469. }
  67470. }
  67471. };
  67472. FreeCameraTouchInput.prototype.getClassName = function () {
  67473. return "FreeCameraTouchInput";
  67474. };
  67475. FreeCameraTouchInput.prototype.getSimpleName = function () {
  67476. return "touch";
  67477. };
  67478. __decorate([
  67479. BABYLON.serialize()
  67480. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  67481. __decorate([
  67482. BABYLON.serialize()
  67483. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  67484. return FreeCameraTouchInput;
  67485. }());
  67486. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  67487. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  67488. })(BABYLON || (BABYLON = {}));
  67489. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  67490. "use strict";
  67491. var BABYLON;
  67492. (function (BABYLON) {
  67493. // We're mainly based on the logic defined into the FreeCamera code
  67494. var TouchCamera = /** @class */ (function (_super) {
  67495. __extends(TouchCamera, _super);
  67496. //-- end properties for backward compatibility for inputs
  67497. function TouchCamera(name, position, scene) {
  67498. var _this = _super.call(this, name, position, scene) || this;
  67499. _this.inputs.addTouch();
  67500. _this._setupInputs();
  67501. return _this;
  67502. }
  67503. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  67504. //-- Begin properties for backward compatibility for inputs
  67505. get: function () {
  67506. var touch = this.inputs.attached["touch"];
  67507. if (touch)
  67508. return touch.touchAngularSensibility;
  67509. return 0;
  67510. },
  67511. set: function (value) {
  67512. var touch = this.inputs.attached["touch"];
  67513. if (touch)
  67514. touch.touchAngularSensibility = value;
  67515. },
  67516. enumerable: true,
  67517. configurable: true
  67518. });
  67519. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  67520. get: function () {
  67521. var touch = this.inputs.attached["touch"];
  67522. if (touch)
  67523. return touch.touchMoveSensibility;
  67524. return 0;
  67525. },
  67526. set: function (value) {
  67527. var touch = this.inputs.attached["touch"];
  67528. if (touch)
  67529. touch.touchMoveSensibility = value;
  67530. },
  67531. enumerable: true,
  67532. configurable: true
  67533. });
  67534. TouchCamera.prototype.getClassName = function () {
  67535. return "TouchCamera";
  67536. };
  67537. TouchCamera.prototype._setupInputs = function () {
  67538. var mouse = this.inputs.attached["mouse"];
  67539. if (mouse) {
  67540. mouse.touchEnabled = false;
  67541. }
  67542. };
  67543. return TouchCamera;
  67544. }(BABYLON.FreeCamera));
  67545. BABYLON.TouchCamera = TouchCamera;
  67546. })(BABYLON || (BABYLON = {}));
  67547. //# sourceMappingURL=babylon.touchCamera.js.map
  67548. "use strict";
  67549. var BABYLON;
  67550. (function (BABYLON) {
  67551. var ProceduralTexture = /** @class */ (function (_super) {
  67552. __extends(ProceduralTexture, _super);
  67553. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  67554. if (fallbackTexture === void 0) { fallbackTexture = null; }
  67555. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67556. if (isCube === void 0) { isCube = false; }
  67557. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67558. _this.isCube = isCube;
  67559. _this.isEnabled = true;
  67560. _this._currentRefreshId = -1;
  67561. _this._refreshRate = 1;
  67562. _this._vertexBuffers = {};
  67563. _this._uniforms = new Array();
  67564. _this._samplers = new Array();
  67565. _this._textures = {};
  67566. _this._floats = {};
  67567. _this._floatsArrays = {};
  67568. _this._colors3 = {};
  67569. _this._colors4 = {};
  67570. _this._vectors2 = {};
  67571. _this._vectors3 = {};
  67572. _this._matrices = {};
  67573. _this._fallbackTextureUsed = false;
  67574. scene.proceduralTextures.push(_this);
  67575. _this._engine = scene.getEngine();
  67576. _this.name = name;
  67577. _this.isRenderTarget = true;
  67578. _this._size = size;
  67579. _this._generateMipMaps = generateMipMaps;
  67580. _this.setFragment(fragment);
  67581. _this._fallbackTexture = fallbackTexture;
  67582. if (isCube) {
  67583. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  67584. _this.setFloat("face", 0);
  67585. }
  67586. else {
  67587. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  67588. }
  67589. // VBO
  67590. var vertices = [];
  67591. vertices.push(1, 1);
  67592. vertices.push(-1, 1);
  67593. vertices.push(-1, -1);
  67594. vertices.push(1, -1);
  67595. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67596. _this._createIndexBuffer();
  67597. return _this;
  67598. }
  67599. ProceduralTexture.prototype._createIndexBuffer = function () {
  67600. var engine = this._engine;
  67601. // Indices
  67602. var indices = [];
  67603. indices.push(0);
  67604. indices.push(1);
  67605. indices.push(2);
  67606. indices.push(0);
  67607. indices.push(2);
  67608. indices.push(3);
  67609. this._indexBuffer = engine.createIndexBuffer(indices);
  67610. };
  67611. ProceduralTexture.prototype._rebuild = function () {
  67612. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67613. if (vb) {
  67614. vb._rebuild();
  67615. }
  67616. this._createIndexBuffer();
  67617. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67618. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67619. }
  67620. };
  67621. ProceduralTexture.prototype.reset = function () {
  67622. if (this._effect === undefined) {
  67623. return;
  67624. }
  67625. var engine = this._engine;
  67626. engine._releaseEffect(this._effect);
  67627. };
  67628. ProceduralTexture.prototype.isReady = function () {
  67629. var _this = this;
  67630. var engine = this._engine;
  67631. var shaders;
  67632. if (!this._fragment) {
  67633. return false;
  67634. }
  67635. if (this._fallbackTextureUsed) {
  67636. return true;
  67637. }
  67638. if (this._fragment.fragmentElement !== undefined) {
  67639. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  67640. }
  67641. else {
  67642. shaders = { vertex: "procedural", fragment: this._fragment };
  67643. }
  67644. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  67645. _this.releaseInternalTexture();
  67646. if (_this._fallbackTexture) {
  67647. _this._texture = _this._fallbackTexture._texture;
  67648. if (_this._texture) {
  67649. _this._texture.incrementReferences();
  67650. }
  67651. }
  67652. _this._fallbackTextureUsed = true;
  67653. });
  67654. return this._effect.isReady();
  67655. };
  67656. ProceduralTexture.prototype.resetRefreshCounter = function () {
  67657. this._currentRefreshId = -1;
  67658. };
  67659. ProceduralTexture.prototype.setFragment = function (fragment) {
  67660. this._fragment = fragment;
  67661. };
  67662. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  67663. get: function () {
  67664. return this._refreshRate;
  67665. },
  67666. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67667. set: function (value) {
  67668. this._refreshRate = value;
  67669. this.resetRefreshCounter();
  67670. },
  67671. enumerable: true,
  67672. configurable: true
  67673. });
  67674. ProceduralTexture.prototype._shouldRender = function () {
  67675. if (!this.isEnabled || !this.isReady() || !this._texture) {
  67676. return false;
  67677. }
  67678. if (this._fallbackTextureUsed) {
  67679. return false;
  67680. }
  67681. if (this._currentRefreshId === -1) {
  67682. this._currentRefreshId = 1;
  67683. return true;
  67684. }
  67685. if (this.refreshRate === this._currentRefreshId) {
  67686. this._currentRefreshId = 1;
  67687. return true;
  67688. }
  67689. this._currentRefreshId++;
  67690. return false;
  67691. };
  67692. ProceduralTexture.prototype.getRenderSize = function () {
  67693. return this._size;
  67694. };
  67695. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  67696. if (this._fallbackTextureUsed) {
  67697. return;
  67698. }
  67699. this.releaseInternalTexture();
  67700. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  67701. };
  67702. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  67703. if (this._uniforms.indexOf(uniformName) === -1) {
  67704. this._uniforms.push(uniformName);
  67705. }
  67706. };
  67707. ProceduralTexture.prototype.setTexture = function (name, texture) {
  67708. if (this._samplers.indexOf(name) === -1) {
  67709. this._samplers.push(name);
  67710. }
  67711. this._textures[name] = texture;
  67712. return this;
  67713. };
  67714. ProceduralTexture.prototype.setFloat = function (name, value) {
  67715. this._checkUniform(name);
  67716. this._floats[name] = value;
  67717. return this;
  67718. };
  67719. ProceduralTexture.prototype.setFloats = function (name, value) {
  67720. this._checkUniform(name);
  67721. this._floatsArrays[name] = value;
  67722. return this;
  67723. };
  67724. ProceduralTexture.prototype.setColor3 = function (name, value) {
  67725. this._checkUniform(name);
  67726. this._colors3[name] = value;
  67727. return this;
  67728. };
  67729. ProceduralTexture.prototype.setColor4 = function (name, value) {
  67730. this._checkUniform(name);
  67731. this._colors4[name] = value;
  67732. return this;
  67733. };
  67734. ProceduralTexture.prototype.setVector2 = function (name, value) {
  67735. this._checkUniform(name);
  67736. this._vectors2[name] = value;
  67737. return this;
  67738. };
  67739. ProceduralTexture.prototype.setVector3 = function (name, value) {
  67740. this._checkUniform(name);
  67741. this._vectors3[name] = value;
  67742. return this;
  67743. };
  67744. ProceduralTexture.prototype.setMatrix = function (name, value) {
  67745. this._checkUniform(name);
  67746. this._matrices[name] = value;
  67747. return this;
  67748. };
  67749. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  67750. var scene = this.getScene();
  67751. if (!scene) {
  67752. return;
  67753. }
  67754. var engine = this._engine;
  67755. // Render
  67756. engine.enableEffect(this._effect);
  67757. engine.setState(false);
  67758. // Texture
  67759. for (var name in this._textures) {
  67760. this._effect.setTexture(name, this._textures[name]);
  67761. }
  67762. // Float
  67763. for (name in this._floats) {
  67764. this._effect.setFloat(name, this._floats[name]);
  67765. }
  67766. // Floats
  67767. for (name in this._floatsArrays) {
  67768. this._effect.setArray(name, this._floatsArrays[name]);
  67769. }
  67770. // Color3
  67771. for (name in this._colors3) {
  67772. this._effect.setColor3(name, this._colors3[name]);
  67773. }
  67774. // Color4
  67775. for (name in this._colors4) {
  67776. var color = this._colors4[name];
  67777. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  67778. }
  67779. // Vector2
  67780. for (name in this._vectors2) {
  67781. this._effect.setVector2(name, this._vectors2[name]);
  67782. }
  67783. // Vector3
  67784. for (name in this._vectors3) {
  67785. this._effect.setVector3(name, this._vectors3[name]);
  67786. }
  67787. // Matrix
  67788. for (name in this._matrices) {
  67789. this._effect.setMatrix(name, this._matrices[name]);
  67790. }
  67791. if (!this._texture) {
  67792. return;
  67793. }
  67794. if (this.isCube) {
  67795. for (var face = 0; face < 6; face++) {
  67796. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  67797. // VBOs
  67798. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67799. this._effect.setFloat("face", face);
  67800. // Clear
  67801. engine.clear(scene.clearColor, true, true, true);
  67802. // Draw order
  67803. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67804. // Mipmaps
  67805. if (face === 5) {
  67806. engine.generateMipMapsForCubemap(this._texture);
  67807. }
  67808. }
  67809. }
  67810. else {
  67811. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  67812. // VBOs
  67813. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67814. // Clear
  67815. engine.clear(scene.clearColor, true, true, true);
  67816. // Draw order
  67817. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67818. }
  67819. // Unbind
  67820. engine.unBindFramebuffer(this._texture, this.isCube);
  67821. if (this.onGenerated) {
  67822. this.onGenerated();
  67823. }
  67824. };
  67825. ProceduralTexture.prototype.clone = function () {
  67826. var textureSize = this.getSize();
  67827. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  67828. // Base texture
  67829. newTexture.hasAlpha = this.hasAlpha;
  67830. newTexture.level = this.level;
  67831. // RenderTarget Texture
  67832. newTexture.coordinatesMode = this.coordinatesMode;
  67833. return newTexture;
  67834. };
  67835. ProceduralTexture.prototype.dispose = function () {
  67836. var scene = this.getScene();
  67837. if (!scene) {
  67838. return;
  67839. }
  67840. var index = scene.proceduralTextures.indexOf(this);
  67841. if (index >= 0) {
  67842. scene.proceduralTextures.splice(index, 1);
  67843. }
  67844. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67845. if (vertexBuffer) {
  67846. vertexBuffer.dispose();
  67847. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67848. }
  67849. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  67850. this._indexBuffer = null;
  67851. }
  67852. _super.prototype.dispose.call(this);
  67853. };
  67854. return ProceduralTexture;
  67855. }(BABYLON.Texture));
  67856. BABYLON.ProceduralTexture = ProceduralTexture;
  67857. })(BABYLON || (BABYLON = {}));
  67858. //# sourceMappingURL=babylon.proceduralTexture.js.map
  67859. "use strict";
  67860. var BABYLON;
  67861. (function (BABYLON) {
  67862. var CustomProceduralTexture = /** @class */ (function (_super) {
  67863. __extends(CustomProceduralTexture, _super);
  67864. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  67865. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  67866. _this._animate = true;
  67867. _this._time = 0;
  67868. _this._texturePath = texturePath;
  67869. //Try to load json
  67870. _this.loadJson(texturePath);
  67871. _this.refreshRate = 1;
  67872. return _this;
  67873. }
  67874. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  67875. var _this = this;
  67876. var noConfigFile = function () {
  67877. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  67878. try {
  67879. _this.setFragment(_this._texturePath);
  67880. }
  67881. catch (ex) {
  67882. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  67883. }
  67884. };
  67885. var configFileUrl = jsonUrl + "/config.json";
  67886. var xhr = new XMLHttpRequest();
  67887. xhr.open("GET", configFileUrl, true);
  67888. xhr.addEventListener("load", function () {
  67889. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67890. try {
  67891. _this._config = JSON.parse(xhr.response);
  67892. _this.updateShaderUniforms();
  67893. _this.updateTextures();
  67894. _this.setFragment(_this._texturePath + "/custom");
  67895. _this._animate = _this._config.animate;
  67896. _this.refreshRate = _this._config.refreshrate;
  67897. }
  67898. catch (ex) {
  67899. noConfigFile();
  67900. }
  67901. }
  67902. else {
  67903. noConfigFile();
  67904. }
  67905. }, false);
  67906. xhr.addEventListener("error", function () {
  67907. noConfigFile();
  67908. }, false);
  67909. try {
  67910. xhr.send();
  67911. }
  67912. catch (ex) {
  67913. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  67914. }
  67915. };
  67916. CustomProceduralTexture.prototype.isReady = function () {
  67917. if (!_super.prototype.isReady.call(this)) {
  67918. return false;
  67919. }
  67920. for (var name in this._textures) {
  67921. var texture = this._textures[name];
  67922. if (!texture.isReady()) {
  67923. return false;
  67924. }
  67925. }
  67926. return true;
  67927. };
  67928. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  67929. var scene = this.getScene();
  67930. if (this._animate && scene) {
  67931. this._time += scene.getAnimationRatio() * 0.03;
  67932. this.updateShaderUniforms();
  67933. }
  67934. _super.prototype.render.call(this, useCameraPostProcess);
  67935. };
  67936. CustomProceduralTexture.prototype.updateTextures = function () {
  67937. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  67938. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  67939. }
  67940. };
  67941. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  67942. if (this._config) {
  67943. for (var j = 0; j < this._config.uniforms.length; j++) {
  67944. var uniform = this._config.uniforms[j];
  67945. switch (uniform.type) {
  67946. case "float":
  67947. this.setFloat(uniform.name, uniform.value);
  67948. break;
  67949. case "color3":
  67950. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  67951. break;
  67952. case "color4":
  67953. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  67954. break;
  67955. case "vector2":
  67956. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  67957. break;
  67958. case "vector3":
  67959. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  67960. break;
  67961. }
  67962. }
  67963. }
  67964. this.setFloat("time", this._time);
  67965. };
  67966. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  67967. get: function () {
  67968. return this._animate;
  67969. },
  67970. set: function (value) {
  67971. this._animate = value;
  67972. },
  67973. enumerable: true,
  67974. configurable: true
  67975. });
  67976. return CustomProceduralTexture;
  67977. }(BABYLON.ProceduralTexture));
  67978. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  67979. })(BABYLON || (BABYLON = {}));
  67980. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  67981. "use strict";
  67982. var BABYLON;
  67983. (function (BABYLON) {
  67984. var FreeCameraGamepadInput = /** @class */ (function () {
  67985. function FreeCameraGamepadInput() {
  67986. this.gamepadAngularSensibility = 200;
  67987. this.gamepadMoveSensibility = 40;
  67988. // private members
  67989. this._cameraTransform = BABYLON.Matrix.Identity();
  67990. this._deltaTransform = BABYLON.Vector3.Zero();
  67991. this._vector3 = BABYLON.Vector3.Zero();
  67992. this._vector2 = BABYLON.Vector2.Zero();
  67993. }
  67994. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  67995. var _this = this;
  67996. var manager = this.camera.getScene().gamepadManager;
  67997. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67998. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  67999. // prioritize XBOX gamepads.
  68000. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68001. _this.gamepad = gamepad;
  68002. }
  68003. }
  68004. });
  68005. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68006. if (_this.gamepad === gamepad) {
  68007. _this.gamepad = null;
  68008. }
  68009. });
  68010. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68011. };
  68012. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68013. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68014. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68015. this.gamepad = null;
  68016. };
  68017. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68018. if (this.gamepad && this.gamepad.leftStick) {
  68019. var camera = this.camera;
  68020. var LSValues = this.gamepad.leftStick;
  68021. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68022. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68023. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68024. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68025. var RSValues = this.gamepad.rightStick;
  68026. if (RSValues) {
  68027. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68028. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68029. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68030. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  68031. }
  68032. else {
  68033. RSValues = { x: 0, y: 0 };
  68034. }
  68035. if (!camera.rotationQuaternion) {
  68036. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  68037. }
  68038. else {
  68039. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  68040. }
  68041. var speed = camera._computeLocalCameraSpeed() * 50.0;
  68042. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  68043. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  68044. camera.cameraDirection.addInPlace(this._deltaTransform);
  68045. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  68046. camera.cameraRotation.addInPlace(this._vector2);
  68047. }
  68048. };
  68049. FreeCameraGamepadInput.prototype.getClassName = function () {
  68050. return "FreeCameraGamepadInput";
  68051. };
  68052. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  68053. return "gamepad";
  68054. };
  68055. __decorate([
  68056. BABYLON.serialize()
  68057. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  68058. __decorate([
  68059. BABYLON.serialize()
  68060. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68061. return FreeCameraGamepadInput;
  68062. }());
  68063. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  68064. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  68065. })(BABYLON || (BABYLON = {}));
  68066. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  68067. "use strict";
  68068. var BABYLON;
  68069. (function (BABYLON) {
  68070. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  68071. function ArcRotateCameraGamepadInput() {
  68072. this.gamepadRotationSensibility = 80;
  68073. this.gamepadMoveSensibility = 40;
  68074. }
  68075. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68076. var _this = this;
  68077. var manager = this.camera.getScene().gamepadManager;
  68078. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68079. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68080. // prioritize XBOX gamepads.
  68081. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68082. _this.gamepad = gamepad;
  68083. }
  68084. }
  68085. });
  68086. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68087. if (_this.gamepad === gamepad) {
  68088. _this.gamepad = null;
  68089. }
  68090. });
  68091. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68092. };
  68093. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  68094. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68095. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68096. this.gamepad = null;
  68097. };
  68098. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  68099. if (this.gamepad) {
  68100. var camera = this.camera;
  68101. var RSValues = this.gamepad.rightStick;
  68102. if (RSValues) {
  68103. if (RSValues.x != 0) {
  68104. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  68105. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  68106. camera.inertialAlphaOffset += normalizedRX;
  68107. }
  68108. }
  68109. if (RSValues.y != 0) {
  68110. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68111. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68112. camera.inertialBetaOffset += normalizedRY;
  68113. }
  68114. }
  68115. }
  68116. var LSValues = this.gamepad.leftStick;
  68117. if (LSValues && LSValues.y != 0) {
  68118. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68119. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68120. this.camera.inertialRadiusOffset -= normalizedLY;
  68121. }
  68122. }
  68123. }
  68124. };
  68125. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68126. return "ArcRotateCameraGamepadInput";
  68127. };
  68128. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68129. return "gamepad";
  68130. };
  68131. __decorate([
  68132. BABYLON.serialize()
  68133. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68134. __decorate([
  68135. BABYLON.serialize()
  68136. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68137. return ArcRotateCameraGamepadInput;
  68138. }());
  68139. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68140. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68141. })(BABYLON || (BABYLON = {}));
  68142. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68143. "use strict";
  68144. var BABYLON;
  68145. (function (BABYLON) {
  68146. var GamepadManager = /** @class */ (function () {
  68147. function GamepadManager(_scene) {
  68148. var _this = this;
  68149. this._scene = _scene;
  68150. this._babylonGamepads = [];
  68151. this._oneGamepadConnected = false;
  68152. this._isMonitoring = false;
  68153. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68154. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68155. this._gamepadEventSupported = false;
  68156. }
  68157. else {
  68158. this._gamepadEventSupported = 'GamepadEvent' in window;
  68159. this._gamepadSupport = (navigator.getGamepads ||
  68160. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68161. }
  68162. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68163. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68164. for (var i in _this._babylonGamepads) {
  68165. var gamepad = _this._babylonGamepads[i];
  68166. if (gamepad && gamepad._isConnected) {
  68167. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68168. }
  68169. }
  68170. });
  68171. this._onGamepadConnectedEvent = function (evt) {
  68172. var gamepad = evt.gamepad;
  68173. if (gamepad.index in _this._babylonGamepads) {
  68174. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68175. return;
  68176. }
  68177. }
  68178. var newGamepad;
  68179. if (_this._babylonGamepads[gamepad.index]) {
  68180. newGamepad = _this._babylonGamepads[gamepad.index];
  68181. newGamepad.browserGamepad = gamepad;
  68182. newGamepad._isConnected = true;
  68183. }
  68184. else {
  68185. newGamepad = _this._addNewGamepad(gamepad);
  68186. }
  68187. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68188. _this._startMonitoringGamepads();
  68189. };
  68190. this._onGamepadDisconnectedEvent = function (evt) {
  68191. var gamepad = evt.gamepad;
  68192. // Remove the gamepad from the list of gamepads to monitor.
  68193. for (var i in _this._babylonGamepads) {
  68194. if (_this._babylonGamepads[i].index === gamepad.index) {
  68195. var disconnectedGamepad = _this._babylonGamepads[i];
  68196. disconnectedGamepad._isConnected = false;
  68197. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68198. break;
  68199. }
  68200. }
  68201. };
  68202. if (this._gamepadSupport) {
  68203. //first add already-connected gamepads
  68204. this._updateGamepadObjects();
  68205. if (this._babylonGamepads.length) {
  68206. this._startMonitoringGamepads();
  68207. }
  68208. // Checking if the gamepad connected event is supported (like in Firefox)
  68209. if (this._gamepadEventSupported) {
  68210. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68211. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68212. }
  68213. else {
  68214. this._startMonitoringGamepads();
  68215. }
  68216. }
  68217. }
  68218. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  68219. get: function () {
  68220. return this._babylonGamepads;
  68221. },
  68222. enumerable: true,
  68223. configurable: true
  68224. });
  68225. GamepadManager.prototype.getGamepadByType = function (type) {
  68226. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  68227. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  68228. var gamepad = _a[_i];
  68229. if (gamepad && gamepad.type === type) {
  68230. return gamepad;
  68231. }
  68232. }
  68233. return null;
  68234. };
  68235. GamepadManager.prototype.dispose = function () {
  68236. if (this._gamepadEventSupported) {
  68237. if (this._onGamepadConnectedEvent) {
  68238. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  68239. }
  68240. if (this._onGamepadDisconnectedEvent) {
  68241. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  68242. }
  68243. this._onGamepadConnectedEvent = null;
  68244. this._onGamepadDisconnectedEvent = null;
  68245. }
  68246. this._babylonGamepads.forEach(function (gamepad) {
  68247. gamepad.dispose();
  68248. });
  68249. this.onGamepadConnectedObservable.clear();
  68250. this.onGamepadDisconnectedObservable.clear();
  68251. this._oneGamepadConnected = false;
  68252. this._stopMonitoringGamepads();
  68253. this._babylonGamepads = [];
  68254. };
  68255. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  68256. if (!this._oneGamepadConnected) {
  68257. this._oneGamepadConnected = true;
  68258. }
  68259. var newGamepad;
  68260. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  68261. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  68262. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  68263. }
  68264. else if (gamepad.pose) {
  68265. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  68266. }
  68267. else {
  68268. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  68269. }
  68270. this._babylonGamepads[newGamepad.index] = newGamepad;
  68271. return newGamepad;
  68272. };
  68273. GamepadManager.prototype._startMonitoringGamepads = function () {
  68274. if (!this._isMonitoring) {
  68275. this._isMonitoring = true;
  68276. //back-comp
  68277. if (!this._scene) {
  68278. this._checkGamepadsStatus();
  68279. }
  68280. }
  68281. };
  68282. GamepadManager.prototype._stopMonitoringGamepads = function () {
  68283. this._isMonitoring = false;
  68284. };
  68285. GamepadManager.prototype._checkGamepadsStatus = function () {
  68286. var _this = this;
  68287. // Hack to be compatible Chrome
  68288. this._updateGamepadObjects();
  68289. for (var i in this._babylonGamepads) {
  68290. var gamepad = this._babylonGamepads[i];
  68291. if (!gamepad || !gamepad.isConnected) {
  68292. continue;
  68293. }
  68294. gamepad.update();
  68295. }
  68296. if (this._isMonitoring && !this._scene) {
  68297. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  68298. }
  68299. };
  68300. // This function is called only on Chrome, which does not properly support
  68301. // connection/disconnection events and forces you to recopy again the gamepad object
  68302. GamepadManager.prototype._updateGamepadObjects = function () {
  68303. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  68304. for (var i = 0; i < gamepads.length; i++) {
  68305. if (gamepads[i]) {
  68306. if (!this._babylonGamepads[gamepads[i].index]) {
  68307. var newGamepad = this._addNewGamepad(gamepads[i]);
  68308. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68309. }
  68310. else {
  68311. // Forced to copy again this object for Chrome for unknown reason
  68312. this._babylonGamepads[i].browserGamepad = gamepads[i];
  68313. if (!this._babylonGamepads[i].isConnected) {
  68314. this._babylonGamepads[i]._isConnected = true;
  68315. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  68316. }
  68317. }
  68318. }
  68319. }
  68320. };
  68321. return GamepadManager;
  68322. }());
  68323. BABYLON.GamepadManager = GamepadManager;
  68324. })(BABYLON || (BABYLON = {}));
  68325. //# sourceMappingURL=babylon.gamepadManager.js.map
  68326. "use strict";
  68327. var BABYLON;
  68328. (function (BABYLON) {
  68329. var StickValues = /** @class */ (function () {
  68330. function StickValues(x, y) {
  68331. this.x = x;
  68332. this.y = y;
  68333. }
  68334. return StickValues;
  68335. }());
  68336. BABYLON.StickValues = StickValues;
  68337. var Gamepad = /** @class */ (function () {
  68338. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  68339. if (leftStickX === void 0) { leftStickX = 0; }
  68340. if (leftStickY === void 0) { leftStickY = 1; }
  68341. if (rightStickX === void 0) { rightStickX = 2; }
  68342. if (rightStickY === void 0) { rightStickY = 3; }
  68343. this.id = id;
  68344. this.index = index;
  68345. this.browserGamepad = browserGamepad;
  68346. this._isConnected = true;
  68347. this._invertLeftStickY = false;
  68348. this.type = Gamepad.GAMEPAD;
  68349. this._leftStickAxisX = leftStickX;
  68350. this._leftStickAxisY = leftStickY;
  68351. this._rightStickAxisX = rightStickX;
  68352. this._rightStickAxisY = rightStickY;
  68353. if (this.browserGamepad.axes.length >= 2) {
  68354. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68355. }
  68356. if (this.browserGamepad.axes.length >= 4) {
  68357. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68358. }
  68359. }
  68360. Object.defineProperty(Gamepad.prototype, "isConnected", {
  68361. get: function () {
  68362. return this._isConnected;
  68363. },
  68364. enumerable: true,
  68365. configurable: true
  68366. });
  68367. Gamepad.prototype.onleftstickchanged = function (callback) {
  68368. this._onleftstickchanged = callback;
  68369. };
  68370. Gamepad.prototype.onrightstickchanged = function (callback) {
  68371. this._onrightstickchanged = callback;
  68372. };
  68373. Object.defineProperty(Gamepad.prototype, "leftStick", {
  68374. get: function () {
  68375. return this._leftStick;
  68376. },
  68377. set: function (newValues) {
  68378. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  68379. this._onleftstickchanged(newValues);
  68380. }
  68381. this._leftStick = newValues;
  68382. },
  68383. enumerable: true,
  68384. configurable: true
  68385. });
  68386. Object.defineProperty(Gamepad.prototype, "rightStick", {
  68387. get: function () {
  68388. return this._rightStick;
  68389. },
  68390. set: function (newValues) {
  68391. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  68392. this._onrightstickchanged(newValues);
  68393. }
  68394. this._rightStick = newValues;
  68395. },
  68396. enumerable: true,
  68397. configurable: true
  68398. });
  68399. Gamepad.prototype.update = function () {
  68400. if (this._leftStick) {
  68401. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68402. if (this._invertLeftStickY) {
  68403. this.leftStick.y *= -1;
  68404. }
  68405. }
  68406. if (this._rightStick) {
  68407. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68408. }
  68409. };
  68410. Gamepad.prototype.dispose = function () {
  68411. };
  68412. Gamepad.GAMEPAD = 0;
  68413. Gamepad.GENERIC = 1;
  68414. Gamepad.XBOX = 2;
  68415. Gamepad.POSE_ENABLED = 3;
  68416. return Gamepad;
  68417. }());
  68418. BABYLON.Gamepad = Gamepad;
  68419. var GenericPad = /** @class */ (function (_super) {
  68420. __extends(GenericPad, _super);
  68421. function GenericPad(id, index, browserGamepad) {
  68422. var _this = _super.call(this, id, index, browserGamepad) || this;
  68423. _this.onButtonDownObservable = new BABYLON.Observable();
  68424. _this.onButtonUpObservable = new BABYLON.Observable();
  68425. _this.type = Gamepad.GENERIC;
  68426. _this._buttons = new Array(browserGamepad.buttons.length);
  68427. return _this;
  68428. }
  68429. GenericPad.prototype.onbuttondown = function (callback) {
  68430. this._onbuttondown = callback;
  68431. };
  68432. GenericPad.prototype.onbuttonup = function (callback) {
  68433. this._onbuttonup = callback;
  68434. };
  68435. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  68436. if (newValue !== currentValue) {
  68437. if (newValue === 1) {
  68438. if (this._onbuttondown) {
  68439. this._onbuttondown(buttonIndex);
  68440. }
  68441. this.onButtonDownObservable.notifyObservers(buttonIndex);
  68442. }
  68443. if (newValue === 0) {
  68444. if (this._onbuttonup) {
  68445. this._onbuttonup(buttonIndex);
  68446. }
  68447. this.onButtonUpObservable.notifyObservers(buttonIndex);
  68448. }
  68449. }
  68450. return newValue;
  68451. };
  68452. GenericPad.prototype.update = function () {
  68453. _super.prototype.update.call(this);
  68454. for (var index = 0; index < this._buttons.length; index++) {
  68455. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  68456. }
  68457. };
  68458. GenericPad.prototype.dispose = function () {
  68459. _super.prototype.dispose.call(this);
  68460. this.onButtonDownObservable.clear();
  68461. this.onButtonUpObservable.clear();
  68462. };
  68463. return GenericPad;
  68464. }(Gamepad));
  68465. BABYLON.GenericPad = GenericPad;
  68466. })(BABYLON || (BABYLON = {}));
  68467. //# sourceMappingURL=babylon.gamepad.js.map
  68468. "use strict";
  68469. var BABYLON;
  68470. (function (BABYLON) {
  68471. var Xbox360Button;
  68472. (function (Xbox360Button) {
  68473. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  68474. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  68475. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  68476. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  68477. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  68478. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  68479. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  68480. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  68481. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  68482. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  68483. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  68484. var Xbox360Dpad;
  68485. (function (Xbox360Dpad) {
  68486. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  68487. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  68488. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  68489. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  68490. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  68491. var Xbox360Pad = /** @class */ (function (_super) {
  68492. __extends(Xbox360Pad, _super);
  68493. function Xbox360Pad(id, index, gamepad, xboxOne) {
  68494. if (xboxOne === void 0) { xboxOne = false; }
  68495. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  68496. _this._leftTrigger = 0;
  68497. _this._rightTrigger = 0;
  68498. _this.onButtonDownObservable = new BABYLON.Observable();
  68499. _this.onButtonUpObservable = new BABYLON.Observable();
  68500. _this.onPadDownObservable = new BABYLON.Observable();
  68501. _this.onPadUpObservable = new BABYLON.Observable();
  68502. _this._buttonA = 0;
  68503. _this._buttonB = 0;
  68504. _this._buttonX = 0;
  68505. _this._buttonY = 0;
  68506. _this._buttonBack = 0;
  68507. _this._buttonStart = 0;
  68508. _this._buttonLB = 0;
  68509. _this._buttonRB = 0;
  68510. _this._buttonLeftStick = 0;
  68511. _this._buttonRightStick = 0;
  68512. _this._dPadUp = 0;
  68513. _this._dPadDown = 0;
  68514. _this._dPadLeft = 0;
  68515. _this._dPadRight = 0;
  68516. _this._isXboxOnePad = false;
  68517. _this.type = BABYLON.Gamepad.XBOX;
  68518. _this._isXboxOnePad = xboxOne;
  68519. return _this;
  68520. }
  68521. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  68522. this._onlefttriggerchanged = callback;
  68523. };
  68524. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  68525. this._onrighttriggerchanged = callback;
  68526. };
  68527. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  68528. get: function () {
  68529. return this._leftTrigger;
  68530. },
  68531. set: function (newValue) {
  68532. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  68533. this._onlefttriggerchanged(newValue);
  68534. }
  68535. this._leftTrigger = newValue;
  68536. },
  68537. enumerable: true,
  68538. configurable: true
  68539. });
  68540. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  68541. get: function () {
  68542. return this._rightTrigger;
  68543. },
  68544. set: function (newValue) {
  68545. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  68546. this._onrighttriggerchanged(newValue);
  68547. }
  68548. this._rightTrigger = newValue;
  68549. },
  68550. enumerable: true,
  68551. configurable: true
  68552. });
  68553. Xbox360Pad.prototype.onbuttondown = function (callback) {
  68554. this._onbuttondown = callback;
  68555. };
  68556. Xbox360Pad.prototype.onbuttonup = function (callback) {
  68557. this._onbuttonup = callback;
  68558. };
  68559. Xbox360Pad.prototype.ondpaddown = function (callback) {
  68560. this._ondpaddown = callback;
  68561. };
  68562. Xbox360Pad.prototype.ondpadup = function (callback) {
  68563. this._ondpadup = callback;
  68564. };
  68565. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  68566. if (newValue !== currentValue) {
  68567. if (newValue === 1) {
  68568. if (this._onbuttondown) {
  68569. this._onbuttondown(buttonType);
  68570. }
  68571. this.onButtonDownObservable.notifyObservers(buttonType);
  68572. }
  68573. if (newValue === 0) {
  68574. if (this._onbuttonup) {
  68575. this._onbuttonup(buttonType);
  68576. }
  68577. this.onButtonUpObservable.notifyObservers(buttonType);
  68578. }
  68579. }
  68580. return newValue;
  68581. };
  68582. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  68583. if (newValue !== currentValue) {
  68584. if (newValue === 1) {
  68585. if (this._ondpaddown) {
  68586. this._ondpaddown(buttonType);
  68587. }
  68588. this.onPadDownObservable.notifyObservers(buttonType);
  68589. }
  68590. if (newValue === 0) {
  68591. if (this._ondpadup) {
  68592. this._ondpadup(buttonType);
  68593. }
  68594. this.onPadUpObservable.notifyObservers(buttonType);
  68595. }
  68596. }
  68597. return newValue;
  68598. };
  68599. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  68600. get: function () {
  68601. return this._buttonA;
  68602. },
  68603. set: function (value) {
  68604. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  68605. },
  68606. enumerable: true,
  68607. configurable: true
  68608. });
  68609. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  68610. get: function () {
  68611. return this._buttonB;
  68612. },
  68613. set: function (value) {
  68614. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  68615. },
  68616. enumerable: true,
  68617. configurable: true
  68618. });
  68619. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  68620. get: function () {
  68621. return this._buttonX;
  68622. },
  68623. set: function (value) {
  68624. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  68625. },
  68626. enumerable: true,
  68627. configurable: true
  68628. });
  68629. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  68630. get: function () {
  68631. return this._buttonY;
  68632. },
  68633. set: function (value) {
  68634. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  68635. },
  68636. enumerable: true,
  68637. configurable: true
  68638. });
  68639. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  68640. get: function () {
  68641. return this._buttonStart;
  68642. },
  68643. set: function (value) {
  68644. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  68645. },
  68646. enumerable: true,
  68647. configurable: true
  68648. });
  68649. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  68650. get: function () {
  68651. return this._buttonBack;
  68652. },
  68653. set: function (value) {
  68654. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  68655. },
  68656. enumerable: true,
  68657. configurable: true
  68658. });
  68659. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  68660. get: function () {
  68661. return this._buttonLB;
  68662. },
  68663. set: function (value) {
  68664. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  68665. },
  68666. enumerable: true,
  68667. configurable: true
  68668. });
  68669. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  68670. get: function () {
  68671. return this._buttonRB;
  68672. },
  68673. set: function (value) {
  68674. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  68675. },
  68676. enumerable: true,
  68677. configurable: true
  68678. });
  68679. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  68680. get: function () {
  68681. return this._buttonLeftStick;
  68682. },
  68683. set: function (value) {
  68684. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  68685. },
  68686. enumerable: true,
  68687. configurable: true
  68688. });
  68689. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  68690. get: function () {
  68691. return this._buttonRightStick;
  68692. },
  68693. set: function (value) {
  68694. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  68695. },
  68696. enumerable: true,
  68697. configurable: true
  68698. });
  68699. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  68700. get: function () {
  68701. return this._dPadUp;
  68702. },
  68703. set: function (value) {
  68704. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  68705. },
  68706. enumerable: true,
  68707. configurable: true
  68708. });
  68709. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  68710. get: function () {
  68711. return this._dPadDown;
  68712. },
  68713. set: function (value) {
  68714. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  68715. },
  68716. enumerable: true,
  68717. configurable: true
  68718. });
  68719. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  68720. get: function () {
  68721. return this._dPadLeft;
  68722. },
  68723. set: function (value) {
  68724. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  68725. },
  68726. enumerable: true,
  68727. configurable: true
  68728. });
  68729. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  68730. get: function () {
  68731. return this._dPadRight;
  68732. },
  68733. set: function (value) {
  68734. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  68735. },
  68736. enumerable: true,
  68737. configurable: true
  68738. });
  68739. Xbox360Pad.prototype.update = function () {
  68740. _super.prototype.update.call(this);
  68741. if (this._isXboxOnePad) {
  68742. this.buttonA = this.browserGamepad.buttons[0].value;
  68743. this.buttonB = this.browserGamepad.buttons[1].value;
  68744. this.buttonX = this.browserGamepad.buttons[2].value;
  68745. this.buttonY = this.browserGamepad.buttons[3].value;
  68746. this.buttonLB = this.browserGamepad.buttons[4].value;
  68747. this.buttonRB = this.browserGamepad.buttons[5].value;
  68748. this.leftTrigger = this.browserGamepad.axes[2];
  68749. this.rightTrigger = this.browserGamepad.axes[5];
  68750. this.buttonBack = this.browserGamepad.buttons[9].value;
  68751. this.buttonStart = this.browserGamepad.buttons[8].value;
  68752. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  68753. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  68754. this.dPadUp = this.browserGamepad.buttons[11].value;
  68755. this.dPadDown = this.browserGamepad.buttons[12].value;
  68756. this.dPadLeft = this.browserGamepad.buttons[13].value;
  68757. this.dPadRight = this.browserGamepad.buttons[14].value;
  68758. }
  68759. else {
  68760. this.buttonA = this.browserGamepad.buttons[0].value;
  68761. this.buttonB = this.browserGamepad.buttons[1].value;
  68762. this.buttonX = this.browserGamepad.buttons[2].value;
  68763. this.buttonY = this.browserGamepad.buttons[3].value;
  68764. this.buttonLB = this.browserGamepad.buttons[4].value;
  68765. this.buttonRB = this.browserGamepad.buttons[5].value;
  68766. this.leftTrigger = this.browserGamepad.buttons[6].value;
  68767. this.rightTrigger = this.browserGamepad.buttons[7].value;
  68768. this.buttonBack = this.browserGamepad.buttons[8].value;
  68769. this.buttonStart = this.browserGamepad.buttons[9].value;
  68770. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  68771. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  68772. this.dPadUp = this.browserGamepad.buttons[12].value;
  68773. this.dPadDown = this.browserGamepad.buttons[13].value;
  68774. this.dPadLeft = this.browserGamepad.buttons[14].value;
  68775. this.dPadRight = this.browserGamepad.buttons[15].value;
  68776. }
  68777. };
  68778. Xbox360Pad.prototype.dispose = function () {
  68779. _super.prototype.dispose.call(this);
  68780. this.onButtonDownObservable.clear();
  68781. this.onButtonUpObservable.clear();
  68782. this.onPadDownObservable.clear();
  68783. this.onPadUpObservable.clear();
  68784. };
  68785. return Xbox360Pad;
  68786. }(BABYLON.Gamepad));
  68787. BABYLON.Xbox360Pad = Xbox360Pad;
  68788. })(BABYLON || (BABYLON = {}));
  68789. //# sourceMappingURL=babylon.xboxGamepad.js.map
  68790. "use strict";
  68791. var BABYLON;
  68792. (function (BABYLON) {
  68793. /**
  68794. * Defines the types of pose enabled controllers that are supported
  68795. */
  68796. var PoseEnabledControllerType;
  68797. (function (PoseEnabledControllerType) {
  68798. /**
  68799. * HTC Vive
  68800. */
  68801. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  68802. /**
  68803. * Oculus Rift
  68804. */
  68805. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  68806. /**
  68807. * Windows mixed reality
  68808. */
  68809. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  68810. /**
  68811. * Samsung gear VR
  68812. */
  68813. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  68814. /**
  68815. * Google Daydream
  68816. */
  68817. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  68818. /**
  68819. * Generic
  68820. */
  68821. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  68822. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  68823. /**
  68824. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  68825. */
  68826. var PoseEnabledControllerHelper = /** @class */ (function () {
  68827. function PoseEnabledControllerHelper() {
  68828. }
  68829. /**
  68830. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  68831. * @param vrGamepad the gamepad to initialized
  68832. * @returns a vr controller of the type the gamepad identified as
  68833. */
  68834. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  68835. // Oculus Touch
  68836. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  68837. return new BABYLON.OculusTouchController(vrGamepad);
  68838. }
  68839. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  68840. return new BABYLON.WindowsMotionController(vrGamepad);
  68841. }
  68842. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  68843. return new BABYLON.ViveController(vrGamepad);
  68844. }
  68845. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  68846. return new BABYLON.GearVRController(vrGamepad);
  68847. }
  68848. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  68849. return new BABYLON.DaydreamController(vrGamepad);
  68850. }
  68851. else {
  68852. return new BABYLON.GenericController(vrGamepad);
  68853. }
  68854. };
  68855. return PoseEnabledControllerHelper;
  68856. }());
  68857. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  68858. /**
  68859. * Defines the PoseEnabledController object that contains state of a vr capable controller
  68860. */
  68861. var PoseEnabledController = /** @class */ (function (_super) {
  68862. __extends(PoseEnabledController, _super);
  68863. /**
  68864. * Creates a new PoseEnabledController from a gamepad
  68865. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  68866. */
  68867. function PoseEnabledController(browserGamepad) {
  68868. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  68869. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  68870. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  68871. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  68872. /**
  68873. * The device position in babylon space
  68874. */
  68875. _this.devicePosition = BABYLON.Vector3.Zero();
  68876. /**
  68877. * The device rotation in babylon space
  68878. */
  68879. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  68880. /**
  68881. * The scale factor of the device in babylon space
  68882. */
  68883. _this.deviceScaleFactor = 1;
  68884. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  68885. /**
  68886. * Internal, matrix used to convert room space to babylon space
  68887. */
  68888. _this._deviceToWorld = BABYLON.Matrix.Identity();
  68889. /**
  68890. * Node to be used when casting a ray from the controller
  68891. */
  68892. _this._pointingPoseNode = null;
  68893. _this._workingMatrix = BABYLON.Matrix.Identity();
  68894. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  68895. _this.controllerType = PoseEnabledControllerType.GENERIC;
  68896. _this.position = BABYLON.Vector3.Zero();
  68897. _this.rotationQuaternion = new BABYLON.Quaternion();
  68898. _this._calculatedPosition = BABYLON.Vector3.Zero();
  68899. _this._calculatedRotation = new BABYLON.Quaternion();
  68900. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  68901. return _this;
  68902. }
  68903. /**
  68904. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  68905. */
  68906. PoseEnabledController.prototype.update = function () {
  68907. _super.prototype.update.call(this);
  68908. var pose = this.browserGamepad.pose;
  68909. this.updateFromDevice(pose);
  68910. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  68911. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  68912. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  68913. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  68914. if (this._mesh) {
  68915. this._mesh.position.copyFrom(this.devicePosition);
  68916. if (this._mesh.rotationQuaternion) {
  68917. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  68918. }
  68919. }
  68920. };
  68921. /**
  68922. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  68923. * @param poseData raw pose fromthe device
  68924. */
  68925. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  68926. if (poseData) {
  68927. this.rawPose = poseData;
  68928. if (poseData.position) {
  68929. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  68930. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  68931. this._deviceRoomPosition.z *= -1;
  68932. }
  68933. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  68934. this._calculatedPosition.addInPlace(this.position);
  68935. }
  68936. var pose = this.rawPose;
  68937. if (poseData.orientation && pose.orientation) {
  68938. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  68939. if (this._mesh) {
  68940. if (this._mesh.getScene().useRightHandedSystem) {
  68941. this._deviceRoomRotationQuaternion.z *= -1;
  68942. this._deviceRoomRotationQuaternion.w *= -1;
  68943. }
  68944. else {
  68945. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  68946. }
  68947. }
  68948. // if the camera is set, rotate to the camera's rotation
  68949. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  68950. }
  68951. }
  68952. };
  68953. /**
  68954. * Attaches a mesh to the controller
  68955. * @param mesh the mesh to be attached
  68956. */
  68957. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  68958. if (this._mesh) {
  68959. this._mesh.parent = null;
  68960. }
  68961. this._mesh = mesh;
  68962. if (this._poseControlledCamera) {
  68963. this._mesh.parent = this._poseControlledCamera;
  68964. }
  68965. if (!this._mesh.rotationQuaternion) {
  68966. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  68967. }
  68968. };
  68969. /**
  68970. * Attaches the controllers mesh to a camera
  68971. * @param camera the camera the mesh should be attached to
  68972. */
  68973. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  68974. this._poseControlledCamera = camera;
  68975. if (this._mesh) {
  68976. this._mesh.parent = this._poseControlledCamera;
  68977. }
  68978. };
  68979. /**
  68980. * Disposes of the controller
  68981. */
  68982. PoseEnabledController.prototype.dispose = function () {
  68983. if (this._mesh) {
  68984. this._mesh.dispose();
  68985. }
  68986. this._mesh = null;
  68987. _super.prototype.dispose.call(this);
  68988. };
  68989. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  68990. /**
  68991. * The mesh that is attached to the controller
  68992. */
  68993. get: function () {
  68994. return this._mesh;
  68995. },
  68996. enumerable: true,
  68997. configurable: true
  68998. });
  68999. /**
  69000. * Gets the ray of the controller in the direction the controller is pointing
  69001. * @param length the length the resulting ray should be
  69002. * @returns a ray in the direction the controller is pointing
  69003. */
  69004. PoseEnabledController.prototype.getForwardRay = function (length) {
  69005. if (length === void 0) { length = 100; }
  69006. if (!this.mesh) {
  69007. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69008. }
  69009. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69010. var origin = m.getTranslation();
  69011. var forward = new BABYLON.Vector3(0, 0, -1);
  69012. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69013. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69014. return new BABYLON.Ray(origin, direction, length);
  69015. };
  69016. /**
  69017. * Name of the child mesh that can be used to cast a ray from the controller
  69018. */
  69019. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69020. return PoseEnabledController;
  69021. }(BABYLON.Gamepad));
  69022. BABYLON.PoseEnabledController = PoseEnabledController;
  69023. })(BABYLON || (BABYLON = {}));
  69024. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69025. "use strict";
  69026. var BABYLON;
  69027. (function (BABYLON) {
  69028. /**
  69029. * Defines the WebVRController object that represents controllers tracked in 3D space
  69030. */
  69031. var WebVRController = /** @class */ (function (_super) {
  69032. __extends(WebVRController, _super);
  69033. /**
  69034. * Creates a new WebVRController from a gamepad
  69035. * @param vrGamepad the gamepad that the WebVRController should be created from
  69036. */
  69037. function WebVRController(vrGamepad) {
  69038. var _this = _super.call(this, vrGamepad) || this;
  69039. // Observables
  69040. /**
  69041. * Fired when the trigger state has changed
  69042. */
  69043. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  69044. /**
  69045. * Fired when the main button state has changed
  69046. */
  69047. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  69048. /**
  69049. * Fired when the secondary button state has changed
  69050. */
  69051. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  69052. /**
  69053. * Fired when the pad state has changed
  69054. */
  69055. _this.onPadStateChangedObservable = new BABYLON.Observable();
  69056. /**
  69057. * Fired when controllers stick values have changed
  69058. */
  69059. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  69060. /**
  69061. * X and Y axis corrisponding to the controllers joystick
  69062. */
  69063. _this.pad = { x: 0, y: 0 };
  69064. // avoid GC, store state in a tmp object
  69065. _this._changes = {
  69066. pressChanged: false,
  69067. touchChanged: false,
  69068. valueChanged: false,
  69069. changed: false
  69070. };
  69071. _this._buttons = new Array(vrGamepad.buttons.length);
  69072. _this.hand = vrGamepad.hand;
  69073. return _this;
  69074. }
  69075. /**
  69076. * Fired when a controller button's state has changed
  69077. * @param callback the callback containing the button that was modified
  69078. */
  69079. WebVRController.prototype.onButtonStateChange = function (callback) {
  69080. this._onButtonStateChange = callback;
  69081. };
  69082. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69083. /**
  69084. * The default controller model for the controller
  69085. */
  69086. get: function () {
  69087. return this._defaultModel;
  69088. },
  69089. enumerable: true,
  69090. configurable: true
  69091. });
  69092. /**
  69093. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  69094. */
  69095. WebVRController.prototype.update = function () {
  69096. _super.prototype.update.call(this);
  69097. for (var index = 0; index < this._buttons.length; index++) {
  69098. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  69099. }
  69100. ;
  69101. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  69102. this.pad.x = this.leftStick.x;
  69103. this.pad.y = this.leftStick.y;
  69104. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  69105. }
  69106. };
  69107. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69108. if (!newState) {
  69109. newState = {
  69110. pressed: false,
  69111. touched: false,
  69112. value: 0
  69113. };
  69114. }
  69115. if (!currentState) {
  69116. this._buttons[buttonIndex] = {
  69117. pressed: newState.pressed,
  69118. touched: newState.touched,
  69119. value: newState.value
  69120. };
  69121. return;
  69122. }
  69123. this._checkChanges(newState, currentState);
  69124. if (this._changes.changed) {
  69125. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69126. this._handleButtonChange(buttonIndex, newState, this._changes);
  69127. }
  69128. this._buttons[buttonIndex].pressed = newState.pressed;
  69129. this._buttons[buttonIndex].touched = newState.touched;
  69130. // oculus triggers are never 0, thou not touched.
  69131. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69132. };
  69133. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69134. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69135. this._changes.touchChanged = newState.touched !== currentState.touched;
  69136. this._changes.valueChanged = newState.value !== currentState.value;
  69137. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69138. return this._changes;
  69139. };
  69140. /**
  69141. * Disposes of th webVRCOntroller
  69142. */
  69143. WebVRController.prototype.dispose = function () {
  69144. _super.prototype.dispose.call(this);
  69145. this.onTriggerStateChangedObservable.clear();
  69146. this.onMainButtonStateChangedObservable.clear();
  69147. this.onSecondaryButtonStateChangedObservable.clear();
  69148. this.onPadStateChangedObservable.clear();
  69149. this.onPadValuesChangedObservable.clear();
  69150. };
  69151. return WebVRController;
  69152. }(BABYLON.PoseEnabledController));
  69153. BABYLON.WebVRController = WebVRController;
  69154. })(BABYLON || (BABYLON = {}));
  69155. //# sourceMappingURL=babylon.webVRController.js.map
  69156. "use strict";
  69157. var BABYLON;
  69158. (function (BABYLON) {
  69159. /**
  69160. * Oculus Touch Controller
  69161. */
  69162. var OculusTouchController = /** @class */ (function (_super) {
  69163. __extends(OculusTouchController, _super);
  69164. /**
  69165. * Creates a new OculusTouchController from a gamepad
  69166. * @param vrGamepad the gamepad that the controller should be created from
  69167. */
  69168. function OculusTouchController(vrGamepad) {
  69169. var _this = _super.call(this, vrGamepad) || this;
  69170. /**
  69171. * Fired when the secondary trigger on this controller is modified
  69172. */
  69173. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69174. /**
  69175. * Fired when the thumb rest on this controller is modified
  69176. */
  69177. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69178. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69179. return _this;
  69180. }
  69181. /**
  69182. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69183. * @param scene scene in which to add meshes
  69184. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69185. */
  69186. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69187. var _this = this;
  69188. var meshName;
  69189. // Hand
  69190. if (this.hand === 'left') {
  69191. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69192. }
  69193. else {
  69194. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69195. }
  69196. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69197. /*
  69198. Parent Mesh name: oculus_touch_left
  69199. - body
  69200. - trigger
  69201. - thumbstick
  69202. - grip
  69203. - button_y
  69204. - button_x
  69205. - button_enter
  69206. */
  69207. _this._defaultModel = newMeshes[1];
  69208. _this.attachToMesh(_this._defaultModel);
  69209. if (meshLoaded) {
  69210. meshLoaded(_this._defaultModel);
  69211. }
  69212. });
  69213. };
  69214. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69215. /**
  69216. * Fired when the A button on this controller is modified
  69217. */
  69218. get: function () {
  69219. if (this.hand === 'right') {
  69220. return this.onMainButtonStateChangedObservable;
  69221. }
  69222. else {
  69223. throw new Error('No A button on left hand');
  69224. }
  69225. },
  69226. enumerable: true,
  69227. configurable: true
  69228. });
  69229. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  69230. /**
  69231. * Fired when the B button on this controller is modified
  69232. */
  69233. get: function () {
  69234. if (this.hand === 'right') {
  69235. return this.onSecondaryButtonStateChangedObservable;
  69236. }
  69237. else {
  69238. throw new Error('No B button on left hand');
  69239. }
  69240. },
  69241. enumerable: true,
  69242. configurable: true
  69243. });
  69244. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  69245. /**
  69246. * Fired when the X button on this controller is modified
  69247. */
  69248. get: function () {
  69249. if (this.hand === 'left') {
  69250. return this.onMainButtonStateChangedObservable;
  69251. }
  69252. else {
  69253. throw new Error('No X button on right hand');
  69254. }
  69255. },
  69256. enumerable: true,
  69257. configurable: true
  69258. });
  69259. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  69260. /**
  69261. * Fired when the Y button on this controller is modified
  69262. */
  69263. get: function () {
  69264. if (this.hand === 'left') {
  69265. return this.onSecondaryButtonStateChangedObservable;
  69266. }
  69267. else {
  69268. throw new Error('No Y button on right hand');
  69269. }
  69270. },
  69271. enumerable: true,
  69272. configurable: true
  69273. });
  69274. /**
  69275. * Called once for each button that changed state since the last frame
  69276. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  69277. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  69278. * 2) secondary trigger (same)
  69279. * 3) A (right) X (left), touch, pressed = value
  69280. * 4) B / Y
  69281. * 5) thumb rest
  69282. * @param buttonIdx Which button index changed
  69283. * @param state New state of the button
  69284. * @param changes Which properties on the state changed since last frame
  69285. */
  69286. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69287. var notifyObject = state; //{ state: state, changes: changes };
  69288. var triggerDirection = this.hand === 'right' ? -1 : 1;
  69289. switch (buttonIdx) {
  69290. case 0:
  69291. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69292. return;
  69293. case 1:// index trigger
  69294. if (this._defaultModel) {
  69295. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  69296. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  69297. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  69298. }
  69299. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69300. return;
  69301. case 2:// secondary trigger
  69302. if (this._defaultModel) {
  69303. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  69304. }
  69305. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  69306. return;
  69307. case 3:
  69308. if (this._defaultModel) {
  69309. if (notifyObject.pressed) {
  69310. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  69311. }
  69312. else {
  69313. (this._defaultModel.getChildren()[1]).position.y = 0;
  69314. }
  69315. }
  69316. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69317. return;
  69318. case 4:
  69319. if (this._defaultModel) {
  69320. if (notifyObject.pressed) {
  69321. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69322. }
  69323. else {
  69324. (this._defaultModel.getChildren()[2]).position.y = 0;
  69325. }
  69326. }
  69327. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69328. return;
  69329. case 5:
  69330. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  69331. return;
  69332. }
  69333. };
  69334. /**
  69335. * Base Url for the controller model.
  69336. */
  69337. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  69338. /**
  69339. * File name for the left controller model.
  69340. */
  69341. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  69342. /**
  69343. * File name for the right controller model.
  69344. */
  69345. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  69346. return OculusTouchController;
  69347. }(BABYLON.WebVRController));
  69348. BABYLON.OculusTouchController = OculusTouchController;
  69349. })(BABYLON || (BABYLON = {}));
  69350. //# sourceMappingURL=babylon.oculusTouchController.js.map
  69351. "use strict";
  69352. var BABYLON;
  69353. (function (BABYLON) {
  69354. /**
  69355. * Vive Controller
  69356. */
  69357. var ViveController = /** @class */ (function (_super) {
  69358. __extends(ViveController, _super);
  69359. /**
  69360. * Creates a new ViveController from a gamepad
  69361. * @param vrGamepad the gamepad that the controller should be created from
  69362. */
  69363. function ViveController(vrGamepad) {
  69364. var _this = _super.call(this, vrGamepad) || this;
  69365. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  69366. _this._invertLeftStickY = true;
  69367. return _this;
  69368. }
  69369. /**
  69370. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69371. * @param scene scene in which to add meshes
  69372. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69373. */
  69374. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69375. var _this = this;
  69376. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  69377. /*
  69378. Parent Mesh name: ViveWand
  69379. - body
  69380. - r_gripper
  69381. - l_gripper
  69382. - menu_button
  69383. - system_button
  69384. - trackpad
  69385. - trigger
  69386. - LED
  69387. */
  69388. _this._defaultModel = newMeshes[1];
  69389. _this.attachToMesh(_this._defaultModel);
  69390. if (meshLoaded) {
  69391. meshLoaded(_this._defaultModel);
  69392. }
  69393. });
  69394. };
  69395. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  69396. /**
  69397. * Fired when the left button on this controller is modified
  69398. */
  69399. get: function () {
  69400. return this.onMainButtonStateChangedObservable;
  69401. },
  69402. enumerable: true,
  69403. configurable: true
  69404. });
  69405. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  69406. /**
  69407. * Fired when the right button on this controller is modified
  69408. */
  69409. get: function () {
  69410. return this.onMainButtonStateChangedObservable;
  69411. },
  69412. enumerable: true,
  69413. configurable: true
  69414. });
  69415. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  69416. /**
  69417. * Fired when the menu button on this controller is modified
  69418. */
  69419. get: function () {
  69420. return this.onSecondaryButtonStateChangedObservable;
  69421. },
  69422. enumerable: true,
  69423. configurable: true
  69424. });
  69425. /**
  69426. * Called once for each button that changed state since the last frame
  69427. * Vive mapping:
  69428. * 0: touchpad
  69429. * 1: trigger
  69430. * 2: left AND right buttons
  69431. * 3: menu button
  69432. * @param buttonIdx Which button index changed
  69433. * @param state New state of the button
  69434. * @param changes Which properties on the state changed since last frame
  69435. */
  69436. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69437. var notifyObject = state; //{ state: state, changes: changes };
  69438. switch (buttonIdx) {
  69439. case 0:
  69440. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69441. return;
  69442. case 1:// index trigger
  69443. if (this._defaultModel) {
  69444. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  69445. }
  69446. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69447. return;
  69448. case 2:// left AND right button
  69449. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69450. return;
  69451. case 3:
  69452. if (this._defaultModel) {
  69453. if (notifyObject.pressed) {
  69454. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69455. }
  69456. else {
  69457. (this._defaultModel.getChildren()[2]).position.y = 0;
  69458. }
  69459. }
  69460. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69461. return;
  69462. }
  69463. };
  69464. /**
  69465. * Base Url for the controller model.
  69466. */
  69467. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  69468. /**
  69469. * File name for the controller model.
  69470. */
  69471. ViveController.MODEL_FILENAME = 'wand.babylon';
  69472. return ViveController;
  69473. }(BABYLON.WebVRController));
  69474. BABYLON.ViveController = ViveController;
  69475. })(BABYLON || (BABYLON = {}));
  69476. //# sourceMappingURL=babylon.viveController.js.map
  69477. "use strict";
  69478. var BABYLON;
  69479. (function (BABYLON) {
  69480. /**
  69481. * Generic Controller
  69482. */
  69483. var GenericController = /** @class */ (function (_super) {
  69484. __extends(GenericController, _super);
  69485. /**
  69486. * Creates a new GenericController from a gamepad
  69487. * @param vrGamepad the gamepad that the controller should be created from
  69488. */
  69489. function GenericController(vrGamepad) {
  69490. return _super.call(this, vrGamepad) || this;
  69491. }
  69492. /**
  69493. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69494. * @param scene scene in which to add meshes
  69495. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69496. */
  69497. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69498. var _this = this;
  69499. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  69500. _this._defaultModel = newMeshes[1];
  69501. _this.attachToMesh(_this._defaultModel);
  69502. if (meshLoaded) {
  69503. meshLoaded(_this._defaultModel);
  69504. }
  69505. });
  69506. };
  69507. /**
  69508. * Called once for each button that changed state since the last frame
  69509. * @param buttonIdx Which button index changed
  69510. * @param state New state of the button
  69511. * @param changes Which properties on the state changed since last frame
  69512. */
  69513. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69514. console.log("Button id: " + buttonIdx + "state: ");
  69515. console.dir(state);
  69516. };
  69517. /**
  69518. * Base Url for the controller model.
  69519. */
  69520. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69521. /**
  69522. * File name for the controller model.
  69523. */
  69524. GenericController.MODEL_FILENAME = 'generic.babylon';
  69525. return GenericController;
  69526. }(BABYLON.WebVRController));
  69527. BABYLON.GenericController = GenericController;
  69528. })(BABYLON || (BABYLON = {}));
  69529. //# sourceMappingURL=babylon.genericController.js.map
  69530. "use strict";
  69531. var BABYLON;
  69532. (function (BABYLON) {
  69533. /**
  69534. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  69535. */
  69536. var LoadedMeshInfo = /** @class */ (function () {
  69537. function LoadedMeshInfo() {
  69538. /**
  69539. * Map of the button meshes contained in the controller
  69540. */
  69541. this.buttonMeshes = {};
  69542. /**
  69543. * Map of the axis meshes contained in the controller
  69544. */
  69545. this.axisMeshes = {};
  69546. }
  69547. return LoadedMeshInfo;
  69548. }());
  69549. /**
  69550. * Defines the WindowsMotionController object that the state of the windows motion controller
  69551. */
  69552. var WindowsMotionController = /** @class */ (function (_super) {
  69553. __extends(WindowsMotionController, _super);
  69554. /**
  69555. * Creates a new WindowsMotionController from a gamepad
  69556. * @param vrGamepad the gamepad that the controller should be created from
  69557. */
  69558. function WindowsMotionController(vrGamepad) {
  69559. var _this = _super.call(this, vrGamepad) || this;
  69560. _this._mapping = {
  69561. // Semantic button names
  69562. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  69563. // A mapping of the button name to glTF model node name
  69564. // that should be transformed by button value.
  69565. buttonMeshNames: {
  69566. 'trigger': 'SELECT',
  69567. 'menu': 'MENU',
  69568. 'grip': 'GRASP',
  69569. 'thumbstick': 'THUMBSTICK_PRESS',
  69570. 'trackpad': 'TOUCHPAD_PRESS'
  69571. },
  69572. // This mapping is used to translate from the Motion Controller to Babylon semantics
  69573. buttonObservableNames: {
  69574. 'trigger': 'onTriggerStateChangedObservable',
  69575. 'menu': 'onSecondaryButtonStateChangedObservable',
  69576. 'grip': 'onMainButtonStateChangedObservable',
  69577. 'thumbstick': 'onPadStateChangedObservable',
  69578. 'trackpad': 'onTrackpadChangedObservable'
  69579. },
  69580. // A mapping of the axis name to glTF model node name
  69581. // that should be transformed by axis value.
  69582. // This array mirrors the browserGamepad.axes array, such that
  69583. // the mesh corresponding to axis 0 is in this array index 0.
  69584. axisMeshNames: [
  69585. 'THUMBSTICK_X',
  69586. 'THUMBSTICK_Y',
  69587. 'TOUCHPAD_TOUCH_X',
  69588. 'TOUCHPAD_TOUCH_Y'
  69589. ],
  69590. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  69591. };
  69592. /**
  69593. * Fired when the trackpad on this controller is clicked
  69594. */
  69595. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  69596. /**
  69597. * Fired when the trackpad on this controller is modified
  69598. */
  69599. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  69600. /**
  69601. * The current x and y values of this controller's trackpad
  69602. */
  69603. _this.trackpad = { x: 0, y: 0 };
  69604. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  69605. _this._loadedMeshInfo = null;
  69606. return _this;
  69607. }
  69608. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  69609. /**
  69610. * Fired when the trigger on this controller is modified
  69611. */
  69612. get: function () {
  69613. return this.onTriggerStateChangedObservable;
  69614. },
  69615. enumerable: true,
  69616. configurable: true
  69617. });
  69618. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  69619. /**
  69620. * Fired when the menu button on this controller is modified
  69621. */
  69622. get: function () {
  69623. return this.onSecondaryButtonStateChangedObservable;
  69624. },
  69625. enumerable: true,
  69626. configurable: true
  69627. });
  69628. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  69629. /**
  69630. * Fired when the grip button on this controller is modified
  69631. */
  69632. get: function () {
  69633. return this.onMainButtonStateChangedObservable;
  69634. },
  69635. enumerable: true,
  69636. configurable: true
  69637. });
  69638. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  69639. /**
  69640. * Fired when the thumbstick button on this controller is modified
  69641. */
  69642. get: function () {
  69643. return this.onPadStateChangedObservable;
  69644. },
  69645. enumerable: true,
  69646. configurable: true
  69647. });
  69648. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  69649. /**
  69650. * Fired when the touchpad button on this controller is modified
  69651. */
  69652. get: function () {
  69653. return this.onTrackpadChangedObservable;
  69654. },
  69655. enumerable: true,
  69656. configurable: true
  69657. });
  69658. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  69659. /**
  69660. * Fired when the touchpad values on this controller are modified
  69661. */
  69662. get: function () {
  69663. return this.onTrackpadValuesChangedObservable;
  69664. },
  69665. enumerable: true,
  69666. configurable: true
  69667. });
  69668. /**
  69669. * Called once per frame by the engine.
  69670. */
  69671. WindowsMotionController.prototype.update = function () {
  69672. _super.prototype.update.call(this);
  69673. if (this.browserGamepad.axes) {
  69674. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  69675. this.trackpad.x = this.browserGamepad["axes"][2];
  69676. this.trackpad.y = this.browserGamepad["axes"][3];
  69677. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  69678. }
  69679. // Only need to animate axes if there is a loaded mesh
  69680. if (this._loadedMeshInfo) {
  69681. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  69682. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  69683. }
  69684. }
  69685. }
  69686. };
  69687. /**
  69688. * Called once for each button that changed state since the last frame
  69689. * @param buttonIdx Which button index changed
  69690. * @param state New state of the button
  69691. * @param changes Which properties on the state changed since last frame
  69692. */
  69693. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69694. var buttonName = this._mapping.buttons[buttonIdx];
  69695. if (!buttonName) {
  69696. return;
  69697. }
  69698. // Only emit events for buttons that we know how to map from index to name
  69699. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  69700. if (observable) {
  69701. observable.notifyObservers(state);
  69702. }
  69703. this._lerpButtonTransform(buttonName, state.value);
  69704. };
  69705. /**
  69706. * Moves the buttons on the controller mesh based on their current state
  69707. * @param buttonName the name of the button to move
  69708. * @param buttonValue the value of the button which determines the buttons new position
  69709. */
  69710. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  69711. // If there is no loaded mesh, there is nothing to transform.
  69712. if (!this._loadedMeshInfo) {
  69713. return;
  69714. }
  69715. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  69716. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  69717. return;
  69718. }
  69719. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  69720. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  69721. };
  69722. /**
  69723. * Moves the axis on the controller mesh based on its current state
  69724. * @param axis the index of the axis
  69725. * @param axisValue the value of the axis which determines the meshes new position
  69726. * @ignore
  69727. */
  69728. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  69729. if (!this._loadedMeshInfo) {
  69730. return;
  69731. }
  69732. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  69733. if (!meshInfo) {
  69734. return;
  69735. }
  69736. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  69737. return;
  69738. }
  69739. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  69740. var lerpValue = axisValue * 0.5 + 0.5;
  69741. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  69742. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  69743. };
  69744. /**
  69745. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69746. * @param scene scene in which to add meshes
  69747. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69748. */
  69749. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  69750. var _this = this;
  69751. if (forceDefault === void 0) { forceDefault = false; }
  69752. var path;
  69753. var filename;
  69754. // Checking if GLB loader is present
  69755. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  69756. // Determine the device specific folder based on the ID suffix
  69757. var device = 'default';
  69758. if (this.id && !forceDefault) {
  69759. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  69760. device = ((match && match[0]) || device);
  69761. }
  69762. // Hand
  69763. if (this.hand === 'left') {
  69764. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  69765. }
  69766. else {
  69767. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  69768. }
  69769. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  69770. }
  69771. else {
  69772. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  69773. path = BABYLON.GenericController.MODEL_BASE_URL;
  69774. filename = BABYLON.GenericController.MODEL_FILENAME;
  69775. }
  69776. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  69777. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  69778. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  69779. if (!_this._loadedMeshInfo) {
  69780. return;
  69781. }
  69782. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  69783. _this.attachToMesh(_this._defaultModel);
  69784. if (meshLoaded) {
  69785. meshLoaded(_this._defaultModel);
  69786. }
  69787. }, null, function (scene, message) {
  69788. BABYLON.Tools.Log(message);
  69789. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  69790. if (!forceDefault) {
  69791. _this.initControllerMesh(scene, meshLoaded, true);
  69792. }
  69793. });
  69794. };
  69795. /**
  69796. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  69797. * can be transformed by button presses and axes values, based on this._mapping.
  69798. *
  69799. * @param scene scene in which the meshes exist
  69800. * @param meshes list of meshes that make up the controller model to process
  69801. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  69802. */
  69803. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  69804. var loadedMeshInfo = null;
  69805. // Create a new mesh to contain the glTF hierarchy
  69806. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  69807. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  69808. var childMesh = null;
  69809. for (var i = 0; i < meshes.length; i++) {
  69810. var mesh = meshes[i];
  69811. if (!mesh.parent) {
  69812. // Exclude controller meshes from picking results
  69813. mesh.isPickable = false;
  69814. // Handle root node, attach to the new parentMesh
  69815. childMesh = mesh;
  69816. break;
  69817. }
  69818. }
  69819. if (childMesh) {
  69820. childMesh.setParent(parentMesh);
  69821. // Create our mesh info. Note that this method will always return non-null.
  69822. loadedMeshInfo = this.createMeshInfo(parentMesh);
  69823. }
  69824. else {
  69825. BABYLON.Tools.Warn('Could not find root node in model file.');
  69826. }
  69827. return loadedMeshInfo;
  69828. };
  69829. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  69830. var loadedMeshInfo = new LoadedMeshInfo();
  69831. var i;
  69832. loadedMeshInfo.rootNode = rootNode;
  69833. // Reset the caches
  69834. loadedMeshInfo.buttonMeshes = {};
  69835. loadedMeshInfo.axisMeshes = {};
  69836. // Button Meshes
  69837. for (i = 0; i < this._mapping.buttons.length; i++) {
  69838. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  69839. if (!buttonMeshName) {
  69840. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  69841. continue;
  69842. }
  69843. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  69844. if (!buttonMesh) {
  69845. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  69846. continue;
  69847. }
  69848. var buttonMeshInfo = {
  69849. index: i,
  69850. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  69851. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  69852. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  69853. };
  69854. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  69855. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  69856. }
  69857. else {
  69858. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  69859. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  69860. '(VALUE: ' + !!buttonMeshInfo.value +
  69861. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  69862. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  69863. ')');
  69864. }
  69865. }
  69866. // Axis Meshes
  69867. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  69868. var axisMeshName = this._mapping.axisMeshNames[i];
  69869. if (!axisMeshName) {
  69870. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  69871. continue;
  69872. }
  69873. var axisMesh = getChildByName(rootNode, axisMeshName);
  69874. if (!axisMesh) {
  69875. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  69876. continue;
  69877. }
  69878. var axisMeshInfo = {
  69879. index: i,
  69880. value: getImmediateChildByName(axisMesh, 'VALUE'),
  69881. min: getImmediateChildByName(axisMesh, 'MIN'),
  69882. max: getImmediateChildByName(axisMesh, 'MAX')
  69883. };
  69884. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  69885. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  69886. }
  69887. else {
  69888. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  69889. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  69890. '(VALUE: ' + !!axisMeshInfo.value +
  69891. ', MIN: ' + !!axisMeshInfo.min +
  69892. ', MAX:' + !!axisMeshInfo.max +
  69893. ')');
  69894. }
  69895. }
  69896. // Pointing Ray
  69897. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  69898. if (!loadedMeshInfo.pointingPoseNode) {
  69899. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  69900. }
  69901. return loadedMeshInfo;
  69902. // Look through all children recursively. This will return null if no mesh exists with the given name.
  69903. function getChildByName(node, name) {
  69904. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  69905. }
  69906. // Look through only immediate children. This will return null if no mesh exists with the given name.
  69907. function getImmediateChildByName(node, name) {
  69908. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  69909. }
  69910. };
  69911. /**
  69912. * Gets the ray of the controller in the direction the controller is pointing
  69913. * @param length the length the resulting ray should be
  69914. * @returns a ray in the direction the controller is pointing
  69915. */
  69916. WindowsMotionController.prototype.getForwardRay = function (length) {
  69917. if (length === void 0) { length = 100; }
  69918. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  69919. return _super.prototype.getForwardRay.call(this, length);
  69920. }
  69921. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  69922. var origin = m.getTranslation();
  69923. var forward = new BABYLON.Vector3(0, 0, -1);
  69924. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69925. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69926. return new BABYLON.Ray(origin, direction, length);
  69927. };
  69928. /**
  69929. * Disposes of the controller
  69930. */
  69931. WindowsMotionController.prototype.dispose = function () {
  69932. _super.prototype.dispose.call(this);
  69933. this.onTrackpadChangedObservable.clear();
  69934. };
  69935. /**
  69936. * The base url used to load the left and right controller models
  69937. */
  69938. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  69939. /**
  69940. * The name of the left controller model file
  69941. */
  69942. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  69943. /**
  69944. * The name of the right controller model file
  69945. */
  69946. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  69947. /**
  69948. * The controller name prefix for this controller type
  69949. */
  69950. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  69951. /**
  69952. * The controller id pattern for this controller type
  69953. */
  69954. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  69955. return WindowsMotionController;
  69956. }(BABYLON.WebVRController));
  69957. BABYLON.WindowsMotionController = WindowsMotionController;
  69958. })(BABYLON || (BABYLON = {}));
  69959. //# sourceMappingURL=babylon.windowsMotionController.js.map
  69960. "use strict";
  69961. var BABYLON;
  69962. (function (BABYLON) {
  69963. /**
  69964. * Gear VR Controller
  69965. */
  69966. var GearVRController = /** @class */ (function (_super) {
  69967. __extends(GearVRController, _super);
  69968. /**
  69969. * Creates a new GearVRController from a gamepad
  69970. * @param vrGamepad the gamepad that the controller should be created from
  69971. */
  69972. function GearVRController(vrGamepad) {
  69973. var _this = _super.call(this, vrGamepad) || this;
  69974. _this._buttonIndexToObservableNameMap = [
  69975. 'onTrackpadChangedObservable',
  69976. 'onTriggerStateChangedObservable' // Trigger
  69977. ];
  69978. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  69979. return _this;
  69980. }
  69981. /**
  69982. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69983. * @param scene scene in which to add meshes
  69984. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69985. */
  69986. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69987. var _this = this;
  69988. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  69989. _this._defaultModel = newMeshes[1];
  69990. _this.attachToMesh(_this._defaultModel);
  69991. if (meshLoaded) {
  69992. meshLoaded(_this._defaultModel);
  69993. }
  69994. });
  69995. };
  69996. /**
  69997. * Called once for each button that changed state since the last frame
  69998. * @param buttonIdx Which button index changed
  69999. * @param state New state of the button
  70000. * @param changes Which properties on the state changed since last frame
  70001. */
  70002. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70003. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70004. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70005. // Only emit events for buttons that we know how to map from index to observable
  70006. var observable = this[observableName];
  70007. if (observable) {
  70008. observable.notifyObservers(state);
  70009. }
  70010. }
  70011. };
  70012. /**
  70013. * Base Url for the controller model.
  70014. */
  70015. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70016. /**
  70017. * File name for the controller model.
  70018. */
  70019. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70020. /**
  70021. * Gamepad Id prefix used to identify this controller.
  70022. */
  70023. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70024. return GearVRController;
  70025. }(BABYLON.WebVRController));
  70026. BABYLON.GearVRController = GearVRController;
  70027. })(BABYLON || (BABYLON = {}));
  70028. //# sourceMappingURL=babylon.gearVRController.js.map
  70029. "use strict";
  70030. var BABYLON;
  70031. (function (BABYLON) {
  70032. /**
  70033. * Google Daydream controller
  70034. */
  70035. var DaydreamController = /** @class */ (function (_super) {
  70036. __extends(DaydreamController, _super);
  70037. /**
  70038. * Creates a new DaydreamController from a gamepad
  70039. * @param vrGamepad the gamepad that the controller should be created from
  70040. */
  70041. function DaydreamController(vrGamepad) {
  70042. var _this = _super.call(this, vrGamepad) || this;
  70043. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  70044. return _this;
  70045. }
  70046. /**
  70047. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70048. * @param scene scene in which to add meshes
  70049. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70050. */
  70051. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70052. var _this = this;
  70053. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  70054. _this._defaultModel = newMeshes[1];
  70055. _this.attachToMesh(_this._defaultModel);
  70056. if (meshLoaded) {
  70057. meshLoaded(_this._defaultModel);
  70058. }
  70059. });
  70060. };
  70061. /**
  70062. * Called once for each button that changed state since the last frame
  70063. * @param buttonIdx Which button index changed
  70064. * @param state New state of the button
  70065. * @param changes Which properties on the state changed since last frame
  70066. */
  70067. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70068. // Daydream controller only has 1 GamepadButton (on the trackpad).
  70069. if (buttonIdx === 0) {
  70070. var observable = this.onTriggerStateChangedObservable;
  70071. if (observable) {
  70072. observable.notifyObservers(state);
  70073. }
  70074. }
  70075. else {
  70076. // If the app or home buttons are ever made available
  70077. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  70078. }
  70079. };
  70080. /**
  70081. * Base Url for the controller model.
  70082. */
  70083. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70084. /**
  70085. * File name for the controller model.
  70086. */
  70087. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70088. /**
  70089. * Gamepad Id prefix used to identify Daydream Controller.
  70090. */
  70091. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70092. return DaydreamController;
  70093. }(BABYLON.WebVRController));
  70094. BABYLON.DaydreamController = DaydreamController;
  70095. })(BABYLON || (BABYLON = {}));
  70096. //# sourceMappingURL=babylon.daydreamController.js.map
  70097. "use strict";
  70098. var BABYLON;
  70099. (function (BABYLON) {
  70100. var FollowCamera = /** @class */ (function (_super) {
  70101. __extends(FollowCamera, _super);
  70102. function FollowCamera(name, position, scene, lockedTarget) {
  70103. if (lockedTarget === void 0) { lockedTarget = null; }
  70104. var _this = _super.call(this, name, position, scene) || this;
  70105. _this.radius = 12;
  70106. _this.rotationOffset = 0;
  70107. _this.heightOffset = 4;
  70108. _this.cameraAcceleration = 0.05;
  70109. _this.maxCameraSpeed = 20;
  70110. _this.lockedTarget = lockedTarget;
  70111. return _this;
  70112. }
  70113. FollowCamera.prototype.getRadians = function (degrees) {
  70114. return degrees * Math.PI / 180;
  70115. };
  70116. FollowCamera.prototype.follow = function (cameraTarget) {
  70117. if (!cameraTarget)
  70118. return;
  70119. var yRotation;
  70120. if (cameraTarget.rotationQuaternion) {
  70121. var rotMatrix = new BABYLON.Matrix();
  70122. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70123. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70124. }
  70125. else {
  70126. yRotation = cameraTarget.rotation.y;
  70127. }
  70128. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70129. var targetPosition = cameraTarget.getAbsolutePosition();
  70130. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70131. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70132. var dx = targetX - this.position.x;
  70133. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70134. var dz = (targetZ) - this.position.z;
  70135. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70136. var vy = dy * this.cameraAcceleration;
  70137. var vz = dz * this.cameraAcceleration * 2;
  70138. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70139. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70140. }
  70141. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70142. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70143. }
  70144. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70145. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70146. }
  70147. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70148. this.setTarget(targetPosition);
  70149. };
  70150. FollowCamera.prototype._checkInputs = function () {
  70151. _super.prototype._checkInputs.call(this);
  70152. if (this.lockedTarget) {
  70153. this.follow(this.lockedTarget);
  70154. }
  70155. };
  70156. FollowCamera.prototype.getClassName = function () {
  70157. return "FollowCamera";
  70158. };
  70159. __decorate([
  70160. BABYLON.serialize()
  70161. ], FollowCamera.prototype, "radius", void 0);
  70162. __decorate([
  70163. BABYLON.serialize()
  70164. ], FollowCamera.prototype, "rotationOffset", void 0);
  70165. __decorate([
  70166. BABYLON.serialize()
  70167. ], FollowCamera.prototype, "heightOffset", void 0);
  70168. __decorate([
  70169. BABYLON.serialize()
  70170. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70171. __decorate([
  70172. BABYLON.serialize()
  70173. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70174. __decorate([
  70175. BABYLON.serializeAsMeshReference("lockedTargetId")
  70176. ], FollowCamera.prototype, "lockedTarget", void 0);
  70177. return FollowCamera;
  70178. }(BABYLON.TargetCamera));
  70179. BABYLON.FollowCamera = FollowCamera;
  70180. var ArcFollowCamera = /** @class */ (function (_super) {
  70181. __extends(ArcFollowCamera, _super);
  70182. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70183. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70184. _this.alpha = alpha;
  70185. _this.beta = beta;
  70186. _this.radius = radius;
  70187. _this.target = target;
  70188. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70189. _this.follow();
  70190. return _this;
  70191. }
  70192. ArcFollowCamera.prototype.follow = function () {
  70193. if (!this.target) {
  70194. return;
  70195. }
  70196. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70197. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70198. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70199. var targetPosition = this.target.getAbsolutePosition();
  70200. this.position = targetPosition.add(this._cartesianCoordinates);
  70201. this.setTarget(targetPosition);
  70202. };
  70203. ArcFollowCamera.prototype._checkInputs = function () {
  70204. _super.prototype._checkInputs.call(this);
  70205. this.follow();
  70206. };
  70207. ArcFollowCamera.prototype.getClassName = function () {
  70208. return "ArcFollowCamera";
  70209. };
  70210. return ArcFollowCamera;
  70211. }(BABYLON.TargetCamera));
  70212. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70213. })(BABYLON || (BABYLON = {}));
  70214. //# sourceMappingURL=babylon.followCamera.js.map
  70215. "use strict";
  70216. var BABYLON;
  70217. (function (BABYLON) {
  70218. // We're mainly based on the logic defined into the FreeCamera code
  70219. var UniversalCamera = /** @class */ (function (_super) {
  70220. __extends(UniversalCamera, _super);
  70221. //-- end properties for backward compatibility for inputs
  70222. function UniversalCamera(name, position, scene) {
  70223. var _this = _super.call(this, name, position, scene) || this;
  70224. _this.inputs.addGamepad();
  70225. return _this;
  70226. }
  70227. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  70228. //-- Begin properties for backward compatibility for inputs
  70229. get: function () {
  70230. var gamepad = this.inputs.attached["gamepad"];
  70231. if (gamepad)
  70232. return gamepad.gamepadAngularSensibility;
  70233. return 0;
  70234. },
  70235. set: function (value) {
  70236. var gamepad = this.inputs.attached["gamepad"];
  70237. if (gamepad)
  70238. gamepad.gamepadAngularSensibility = value;
  70239. },
  70240. enumerable: true,
  70241. configurable: true
  70242. });
  70243. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  70244. get: function () {
  70245. var gamepad = this.inputs.attached["gamepad"];
  70246. if (gamepad)
  70247. return gamepad.gamepadMoveSensibility;
  70248. return 0;
  70249. },
  70250. set: function (value) {
  70251. var gamepad = this.inputs.attached["gamepad"];
  70252. if (gamepad)
  70253. gamepad.gamepadMoveSensibility = value;
  70254. },
  70255. enumerable: true,
  70256. configurable: true
  70257. });
  70258. UniversalCamera.prototype.getClassName = function () {
  70259. return "UniversalCamera";
  70260. };
  70261. return UniversalCamera;
  70262. }(BABYLON.TouchCamera));
  70263. BABYLON.UniversalCamera = UniversalCamera;
  70264. })(BABYLON || (BABYLON = {}));
  70265. //# sourceMappingURL=babylon.universalCamera.js.map
  70266. "use strict";
  70267. var BABYLON;
  70268. (function (BABYLON) {
  70269. // We're mainly based on the logic defined into the FreeCamera code
  70270. var GamepadCamera = /** @class */ (function (_super) {
  70271. __extends(GamepadCamera, _super);
  70272. //-- end properties for backward compatibility for inputs
  70273. function GamepadCamera(name, position, scene) {
  70274. return _super.call(this, name, position, scene) || this;
  70275. }
  70276. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  70277. //-- Begin properties for backward compatibility for inputs
  70278. get: function () {
  70279. var gamepad = this.inputs.attached["gamepad"];
  70280. if (gamepad)
  70281. return gamepad.gamepadAngularSensibility;
  70282. return 0;
  70283. },
  70284. set: function (value) {
  70285. var gamepad = this.inputs.attached["gamepad"];
  70286. if (gamepad)
  70287. gamepad.gamepadAngularSensibility = value;
  70288. },
  70289. enumerable: true,
  70290. configurable: true
  70291. });
  70292. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  70293. get: function () {
  70294. var gamepad = this.inputs.attached["gamepad"];
  70295. if (gamepad)
  70296. return gamepad.gamepadMoveSensibility;
  70297. return 0;
  70298. },
  70299. set: function (value) {
  70300. var gamepad = this.inputs.attached["gamepad"];
  70301. if (gamepad)
  70302. gamepad.gamepadMoveSensibility = value;
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. GamepadCamera.prototype.getClassName = function () {
  70308. return "GamepadCamera";
  70309. };
  70310. return GamepadCamera;
  70311. }(BABYLON.UniversalCamera));
  70312. BABYLON.GamepadCamera = GamepadCamera;
  70313. })(BABYLON || (BABYLON = {}));
  70314. //# sourceMappingURL=babylon.gamepadCamera.js.map
  70315. "use strict";
  70316. var BABYLON;
  70317. (function (BABYLON) {
  70318. var PostProcessRenderPipelineManager = /** @class */ (function () {
  70319. function PostProcessRenderPipelineManager() {
  70320. this._renderPipelines = {};
  70321. }
  70322. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  70323. this._renderPipelines[renderPipeline._name] = renderPipeline;
  70324. };
  70325. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  70326. if (unique === void 0) { unique = false; }
  70327. var renderPipeline = this._renderPipelines[renderPipelineName];
  70328. if (!renderPipeline) {
  70329. return;
  70330. }
  70331. renderPipeline._attachCameras(cameras, unique);
  70332. };
  70333. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  70334. var renderPipeline = this._renderPipelines[renderPipelineName];
  70335. if (!renderPipeline) {
  70336. return;
  70337. }
  70338. renderPipeline._detachCameras(cameras);
  70339. };
  70340. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70341. var renderPipeline = this._renderPipelines[renderPipelineName];
  70342. if (!renderPipeline) {
  70343. return;
  70344. }
  70345. renderPipeline._enableEffect(renderEffectName, cameras);
  70346. };
  70347. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70348. var renderPipeline = this._renderPipelines[renderPipelineName];
  70349. if (!renderPipeline) {
  70350. return;
  70351. }
  70352. renderPipeline._disableEffect(renderEffectName, cameras);
  70353. };
  70354. PostProcessRenderPipelineManager.prototype.update = function () {
  70355. for (var renderPipelineName in this._renderPipelines) {
  70356. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70357. var pipeline = this._renderPipelines[renderPipelineName];
  70358. if (!pipeline.isSupported) {
  70359. pipeline.dispose();
  70360. delete this._renderPipelines[renderPipelineName];
  70361. }
  70362. else {
  70363. pipeline._update();
  70364. }
  70365. }
  70366. }
  70367. };
  70368. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  70369. for (var renderPipelineName in this._renderPipelines) {
  70370. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70371. var pipeline = this._renderPipelines[renderPipelineName];
  70372. pipeline._rebuild();
  70373. }
  70374. }
  70375. };
  70376. PostProcessRenderPipelineManager.prototype.dispose = function () {
  70377. for (var renderPipelineName in this._renderPipelines) {
  70378. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70379. var pipeline = this._renderPipelines[renderPipelineName];
  70380. pipeline.dispose();
  70381. }
  70382. }
  70383. };
  70384. return PostProcessRenderPipelineManager;
  70385. }());
  70386. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  70387. })(BABYLON || (BABYLON = {}));
  70388. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  70389. "use strict";
  70390. var BABYLON;
  70391. (function (BABYLON) {
  70392. /**
  70393. * This represents a set of one or more post processes in Babylon.
  70394. * A post process can be used to apply a shader to a texture after it is rendered.
  70395. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  70396. */
  70397. var PostProcessRenderEffect = /** @class */ (function () {
  70398. /**
  70399. * Instantiates a post process render effect.
  70400. * A post process can be used to apply a shader to a texture after it is rendered.
  70401. * @param engine The engine the effect is tied to
  70402. * @param name The name of the effect
  70403. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  70404. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  70405. */
  70406. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  70407. this._name = name;
  70408. this._singleInstance = singleInstance || true;
  70409. this._getPostProcesses = getPostProcesses;
  70410. this._cameras = {};
  70411. this._indicesForCamera = {};
  70412. this._postProcesses = {};
  70413. }
  70414. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  70415. /**
  70416. * Checks if all the post processes in the effect are supported.
  70417. */
  70418. get: function () {
  70419. for (var index in this._postProcesses) {
  70420. for (var ppIndex in this._postProcesses[index]) {
  70421. if (!this._postProcesses[index][ppIndex].isSupported) {
  70422. return false;
  70423. }
  70424. }
  70425. }
  70426. return true;
  70427. },
  70428. enumerable: true,
  70429. configurable: true
  70430. });
  70431. /**
  70432. * Updates the current state of the effect
  70433. */
  70434. PostProcessRenderEffect.prototype._update = function () {
  70435. };
  70436. /**
  70437. * Attaches the effect on cameras
  70438. * @param cameras The camera to attach to.
  70439. */
  70440. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  70441. var _this = this;
  70442. var cameraKey;
  70443. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70444. if (!cams) {
  70445. return;
  70446. }
  70447. for (var i = 0; i < cams.length; i++) {
  70448. var camera = cams[i];
  70449. var cameraName = camera.name;
  70450. if (this._singleInstance) {
  70451. cameraKey = 0;
  70452. }
  70453. else {
  70454. cameraKey = cameraName;
  70455. }
  70456. if (!this._postProcesses[cameraKey]) {
  70457. var postProcess = this._getPostProcesses();
  70458. if (postProcess) {
  70459. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  70460. }
  70461. }
  70462. if (!this._indicesForCamera[cameraName]) {
  70463. this._indicesForCamera[cameraName] = [];
  70464. }
  70465. this._postProcesses[cameraKey].forEach(function (postProcess) {
  70466. var index = camera.attachPostProcess(postProcess);
  70467. _this._indicesForCamera[cameraName].push(index);
  70468. });
  70469. if (!this._cameras[cameraName]) {
  70470. this._cameras[cameraName] = camera;
  70471. }
  70472. }
  70473. };
  70474. /**
  70475. * Detatches the effect on cameras
  70476. * @param cameras The camera to detatch from.
  70477. */
  70478. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  70479. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70480. if (!cams) {
  70481. return;
  70482. }
  70483. for (var i = 0; i < cams.length; i++) {
  70484. var camera = cams[i];
  70485. var cameraName = camera.name;
  70486. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70487. camera.detachPostProcess(postProcess);
  70488. });
  70489. if (this._cameras[cameraName]) {
  70490. //this._indicesForCamera.splice(index, 1);
  70491. this._cameras[cameraName] = null;
  70492. }
  70493. }
  70494. };
  70495. /**
  70496. * Enables the effect on given cameras
  70497. * @param cameras The camera to enable.
  70498. */
  70499. PostProcessRenderEffect.prototype._enable = function (cameras) {
  70500. var _this = this;
  70501. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70502. if (!cams) {
  70503. return;
  70504. }
  70505. for (var i = 0; i < cams.length; i++) {
  70506. var camera = cams[i];
  70507. var cameraName = camera.name;
  70508. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  70509. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  70510. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70511. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  70512. });
  70513. }
  70514. }
  70515. }
  70516. };
  70517. /**
  70518. * Disables the effect on the given cameras
  70519. * @param cameras The camera to disable.
  70520. */
  70521. PostProcessRenderEffect.prototype._disable = function (cameras) {
  70522. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70523. if (!cams) {
  70524. return;
  70525. }
  70526. for (var i = 0; i < cams.length; i++) {
  70527. var camera = cams[i];
  70528. var cameraName = camera.name;
  70529. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70530. camera.detachPostProcess(postProcess);
  70531. });
  70532. }
  70533. };
  70534. /**
  70535. * Gets a list of the post processes contained in the effect.
  70536. * @param camera The camera to get the post processes on.
  70537. * @returns The list of the post processes in the effect.
  70538. */
  70539. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  70540. if (this._singleInstance) {
  70541. return this._postProcesses[0];
  70542. }
  70543. else {
  70544. if (!camera) {
  70545. return null;
  70546. }
  70547. return this._postProcesses[camera.name];
  70548. }
  70549. };
  70550. return PostProcessRenderEffect;
  70551. }());
  70552. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  70553. })(BABYLON || (BABYLON = {}));
  70554. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  70555. "use strict";
  70556. var BABYLON;
  70557. (function (BABYLON) {
  70558. var PostProcessRenderPipeline = /** @class */ (function () {
  70559. function PostProcessRenderPipeline(engine, name) {
  70560. this.engine = engine;
  70561. this._name = name;
  70562. this._renderEffects = {};
  70563. this._renderEffectsForIsolatedPass = new Array();
  70564. this._cameras = [];
  70565. }
  70566. PostProcessRenderPipeline.prototype.getClassName = function () {
  70567. return "PostProcessRenderPipeline";
  70568. };
  70569. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  70570. get: function () {
  70571. for (var renderEffectName in this._renderEffects) {
  70572. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70573. if (!this._renderEffects[renderEffectName].isSupported) {
  70574. return false;
  70575. }
  70576. }
  70577. }
  70578. return true;
  70579. },
  70580. enumerable: true,
  70581. configurable: true
  70582. });
  70583. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  70584. this._renderEffects[renderEffect._name] = renderEffect;
  70585. };
  70586. // private
  70587. PostProcessRenderPipeline.prototype._rebuild = function () {
  70588. };
  70589. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  70590. var renderEffects = this._renderEffects[renderEffectName];
  70591. if (!renderEffects) {
  70592. return;
  70593. }
  70594. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  70595. };
  70596. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  70597. var renderEffects = this._renderEffects[renderEffectName];
  70598. if (!renderEffects) {
  70599. return;
  70600. }
  70601. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  70602. };
  70603. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  70604. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70605. if (!cams) {
  70606. return;
  70607. }
  70608. var indicesToDelete = [];
  70609. var i;
  70610. for (i = 0; i < cams.length; i++) {
  70611. var camera = cams[i];
  70612. var cameraName = camera.name;
  70613. if (this._cameras.indexOf(camera) === -1) {
  70614. this._cameras[cameraName] = camera;
  70615. }
  70616. else if (unique) {
  70617. indicesToDelete.push(i);
  70618. }
  70619. }
  70620. for (i = 0; i < indicesToDelete.length; i++) {
  70621. cameras.splice(indicesToDelete[i], 1);
  70622. }
  70623. for (var renderEffectName in this._renderEffects) {
  70624. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70625. this._renderEffects[renderEffectName]._attachCameras(cams);
  70626. }
  70627. }
  70628. };
  70629. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  70630. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70631. if (!cams) {
  70632. return;
  70633. }
  70634. for (var renderEffectName in this._renderEffects) {
  70635. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70636. this._renderEffects[renderEffectName]._detachCameras(cams);
  70637. }
  70638. }
  70639. for (var i = 0; i < cams.length; i++) {
  70640. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  70641. }
  70642. };
  70643. PostProcessRenderPipeline.prototype._update = function () {
  70644. for (var renderEffectName in this._renderEffects) {
  70645. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70646. this._renderEffects[renderEffectName]._update();
  70647. }
  70648. }
  70649. for (var i = 0; i < this._cameras.length; i++) {
  70650. var cameraName = this._cameras[i].name;
  70651. if (this._renderEffectsForIsolatedPass[cameraName]) {
  70652. this._renderEffectsForIsolatedPass[cameraName]._update();
  70653. }
  70654. }
  70655. };
  70656. PostProcessRenderPipeline.prototype._reset = function () {
  70657. this._renderEffects = {};
  70658. this._renderEffectsForIsolatedPass = new Array();
  70659. };
  70660. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  70661. // 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)
  70662. var effectKeys = Object.keys(this._renderEffects);
  70663. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  70664. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  70665. if (postProcesses) {
  70666. postProcesses[0].samples = sampleCount;
  70667. return true;
  70668. }
  70669. }
  70670. return false;
  70671. };
  70672. PostProcessRenderPipeline.prototype.dispose = function () {
  70673. // Must be implemented by children
  70674. };
  70675. __decorate([
  70676. BABYLON.serialize()
  70677. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  70678. return PostProcessRenderPipeline;
  70679. }());
  70680. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  70681. })(BABYLON || (BABYLON = {}));
  70682. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  70683. "use strict";
  70684. var BABYLON;
  70685. (function (BABYLON) {
  70686. /**
  70687. * This represents a depth renderer in Babylon.
  70688. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  70689. */
  70690. var DepthRenderer = /** @class */ (function () {
  70691. /**
  70692. * Instantiates a depth renderer
  70693. * @param scene The scene the renderer belongs to
  70694. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  70695. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  70696. */
  70697. function DepthRenderer(scene, type, camera) {
  70698. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  70699. if (camera === void 0) { camera = null; }
  70700. var _this = this;
  70701. this._scene = scene;
  70702. this._camera = camera;
  70703. var engine = scene.getEngine();
  70704. // Render target
  70705. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  70706. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70707. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70708. this._depthMap.refreshRate = 1;
  70709. this._depthMap.renderParticles = false;
  70710. this._depthMap.renderList = null;
  70711. // Camera to get depth map from to support multiple concurrent cameras
  70712. this._depthMap.activeCamera = this._camera;
  70713. this._depthMap.ignoreCameraViewport = true;
  70714. this._depthMap.useCameraPostProcesses = false;
  70715. // set default depth value to 1.0 (far away)
  70716. this._depthMap.onClearObservable.add(function (engine) {
  70717. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  70718. });
  70719. // Custom render function
  70720. var renderSubMesh = function (subMesh) {
  70721. var mesh = subMesh.getRenderingMesh();
  70722. var scene = _this._scene;
  70723. var engine = scene.getEngine();
  70724. var material = subMesh.getMaterial();
  70725. if (!material) {
  70726. return;
  70727. }
  70728. // Culling and reverse (right handed system)
  70729. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70730. // Managing instances
  70731. var batch = mesh._getInstancesRenderList(subMesh._id);
  70732. if (batch.mustReturn) {
  70733. return;
  70734. }
  70735. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70736. var camera = _this._camera || scene.activeCamera;
  70737. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  70738. engine.enableEffect(_this._effect);
  70739. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70740. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70741. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  70742. // Alpha test
  70743. if (material && material.needAlphaTesting()) {
  70744. var alphaTexture = material.getAlphaTestTexture();
  70745. if (alphaTexture) {
  70746. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70747. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70748. }
  70749. }
  70750. // Bones
  70751. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70752. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70753. }
  70754. // Draw
  70755. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70756. }
  70757. };
  70758. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70759. var index;
  70760. if (depthOnlySubMeshes.length) {
  70761. engine.setColorWrite(false);
  70762. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70763. renderSubMesh(depthOnlySubMeshes.data[index]);
  70764. }
  70765. engine.setColorWrite(true);
  70766. }
  70767. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70768. renderSubMesh(opaqueSubMeshes.data[index]);
  70769. }
  70770. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70771. renderSubMesh(alphaTestSubMeshes.data[index]);
  70772. }
  70773. };
  70774. }
  70775. /**
  70776. * Creates the depth rendering effect and checks if the effect is ready.
  70777. * @param subMesh The submesh to be used to render the depth map of
  70778. * @param useInstances If multiple world instances should be used
  70779. * @returns if the depth renderer is ready to render the depth map
  70780. */
  70781. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  70782. var material = subMesh.getMaterial();
  70783. if (material.disableDepthWrite) {
  70784. return false;
  70785. }
  70786. var defines = [];
  70787. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70788. var mesh = subMesh.getMesh();
  70789. // Alpha test
  70790. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  70791. defines.push("#define ALPHATEST");
  70792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70793. attribs.push(BABYLON.VertexBuffer.UVKind);
  70794. defines.push("#define UV1");
  70795. }
  70796. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70797. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70798. defines.push("#define UV2");
  70799. }
  70800. }
  70801. // Bones
  70802. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70803. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70804. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70805. if (mesh.numBoneInfluencers > 4) {
  70806. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70807. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70808. }
  70809. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70810. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70811. }
  70812. else {
  70813. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70814. }
  70815. // Instances
  70816. if (useInstances) {
  70817. defines.push("#define INSTANCES");
  70818. attribs.push("world0");
  70819. attribs.push("world1");
  70820. attribs.push("world2");
  70821. attribs.push("world3");
  70822. }
  70823. // Get correct effect
  70824. var join = defines.join("\n");
  70825. if (this._cachedDefines !== join) {
  70826. this._cachedDefines = join;
  70827. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  70828. }
  70829. return this._effect.isReady();
  70830. };
  70831. /**
  70832. * Gets the texture which the depth map will be written to.
  70833. * @returns The depth map texture
  70834. */
  70835. DepthRenderer.prototype.getDepthMap = function () {
  70836. return this._depthMap;
  70837. };
  70838. /**
  70839. * Disposes of the depth renderer.
  70840. */
  70841. DepthRenderer.prototype.dispose = function () {
  70842. this._depthMap.dispose();
  70843. };
  70844. return DepthRenderer;
  70845. }());
  70846. BABYLON.DepthRenderer = DepthRenderer;
  70847. })(BABYLON || (BABYLON = {}));
  70848. //# sourceMappingURL=babylon.depthRenderer.js.map
  70849. "use strict";
  70850. var BABYLON;
  70851. (function (BABYLON) {
  70852. var SSAORenderingPipeline = /** @class */ (function (_super) {
  70853. __extends(SSAORenderingPipeline, _super);
  70854. /**
  70855. * @constructor
  70856. * @param {string} name - The rendering pipeline name
  70857. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70858. * @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 }
  70859. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70860. */
  70861. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  70862. var _this = _super.call(this, scene.getEngine(), name) || this;
  70863. // Members
  70864. /**
  70865. * The PassPostProcess id in the pipeline that contains the original scene color
  70866. */
  70867. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  70868. /**
  70869. * The SSAO PostProcess id in the pipeline
  70870. */
  70871. _this.SSAORenderEffect = "SSAORenderEffect";
  70872. /**
  70873. * The horizontal blur PostProcess id in the pipeline
  70874. */
  70875. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  70876. /**
  70877. * The vertical blur PostProcess id in the pipeline
  70878. */
  70879. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  70880. /**
  70881. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  70882. */
  70883. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  70884. /**
  70885. * The output strength of the SSAO post-process. Default value is 1.0.
  70886. */
  70887. _this.totalStrength = 1.0;
  70888. /**
  70889. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  70890. */
  70891. _this.radius = 0.0001;
  70892. /**
  70893. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  70894. * Must not be equal to fallOff and superior to fallOff.
  70895. * Default value is 0.975
  70896. */
  70897. _this.area = 0.0075;
  70898. /**
  70899. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  70900. * Must not be equal to area and inferior to area.
  70901. * Default value is 0.0
  70902. */
  70903. _this.fallOff = 0.000001;
  70904. /**
  70905. * The base color of the SSAO post-process
  70906. * The final result is "base + ssao" between [0, 1]
  70907. */
  70908. _this.base = 0.5;
  70909. _this._firstUpdate = true;
  70910. _this._scene = scene;
  70911. // Set up assets
  70912. _this._createRandomTexture();
  70913. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  70914. var ssaoRatio = ratio.ssaoRatio || ratio;
  70915. var combineRatio = ratio.combineRatio || ratio;
  70916. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  70917. _this._createSSAOPostProcess(ssaoRatio);
  70918. _this._createBlurPostProcess(ssaoRatio);
  70919. _this._createSSAOCombinePostProcess(combineRatio);
  70920. // Set up pipeline
  70921. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  70922. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  70923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  70924. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  70925. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  70926. // Finish
  70927. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70928. if (cameras)
  70929. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  70930. return _this;
  70931. }
  70932. // Public Methods
  70933. /**
  70934. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  70935. */
  70936. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  70937. if (disableDepthRender === void 0) { disableDepthRender = false; }
  70938. for (var i = 0; i < this._scene.cameras.length; i++) {
  70939. var camera = this._scene.cameras[i];
  70940. this._originalColorPostProcess.dispose(camera);
  70941. this._ssaoPostProcess.dispose(camera);
  70942. this._blurHPostProcess.dispose(camera);
  70943. this._blurVPostProcess.dispose(camera);
  70944. this._ssaoCombinePostProcess.dispose(camera);
  70945. }
  70946. this._randomTexture.dispose();
  70947. if (disableDepthRender)
  70948. this._scene.disableDepthRenderer();
  70949. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  70950. _super.prototype.dispose.call(this);
  70951. };
  70952. // Private Methods
  70953. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  70954. var _this = this;
  70955. var size = 16;
  70956. 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);
  70957. 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);
  70958. this._blurHPostProcess.onActivateObservable.add(function () {
  70959. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  70960. _this._blurHPostProcess.kernel = size * dw;
  70961. });
  70962. this._blurVPostProcess.onActivateObservable.add(function () {
  70963. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  70964. _this._blurVPostProcess.kernel = size * dw;
  70965. });
  70966. };
  70967. SSAORenderingPipeline.prototype._rebuild = function () {
  70968. this._firstUpdate = true;
  70969. _super.prototype._rebuild.call(this);
  70970. };
  70971. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  70972. var _this = this;
  70973. var numSamples = 16;
  70974. var sampleSphere = [
  70975. 0.5381, 0.1856, -0.4319,
  70976. 0.1379, 0.2486, 0.4430,
  70977. 0.3371, 0.5679, -0.0057,
  70978. -0.6999, -0.0451, -0.0019,
  70979. 0.0689, -0.1598, -0.8547,
  70980. 0.0560, 0.0069, -0.1843,
  70981. -0.0146, 0.1402, 0.0762,
  70982. 0.0100, -0.1924, -0.0344,
  70983. -0.3577, -0.5301, -0.4358,
  70984. -0.3169, 0.1063, 0.0158,
  70985. 0.0103, -0.5869, 0.0046,
  70986. -0.0897, -0.4940, 0.3287,
  70987. 0.7119, -0.0154, -0.0918,
  70988. -0.0533, 0.0596, -0.5411,
  70989. 0.0352, -0.0631, 0.5460,
  70990. -0.4776, 0.2847, -0.0271
  70991. ];
  70992. var samplesFactor = 1.0 / numSamples;
  70993. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  70994. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  70995. "area", "fallOff", "base", "range", "viewport"
  70996. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  70997. this._ssaoPostProcess.onApply = function (effect) {
  70998. if (_this._firstUpdate) {
  70999. effect.setArray3("sampleSphere", sampleSphere);
  71000. effect.setFloat("samplesFactor", samplesFactor);
  71001. effect.setFloat("randTextureTiles", 4.0);
  71002. }
  71003. effect.setFloat("totalStrength", _this.totalStrength);
  71004. effect.setFloat("radius", _this.radius);
  71005. effect.setFloat("area", _this.area);
  71006. effect.setFloat("fallOff", _this.fallOff);
  71007. effect.setFloat("base", _this.base);
  71008. effect.setTexture("textureSampler", _this._depthTexture);
  71009. effect.setTexture("randomSampler", _this._randomTexture);
  71010. };
  71011. };
  71012. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71013. var _this = this;
  71014. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71015. this._ssaoCombinePostProcess.onApply = function (effect) {
  71016. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71017. };
  71018. };
  71019. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71020. var size = 512;
  71021. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71022. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71023. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71024. var context = this._randomTexture.getContext();
  71025. var rand = function (min, max) {
  71026. return Math.random() * (max - min) + min;
  71027. };
  71028. var randVector = BABYLON.Vector3.Zero();
  71029. for (var x = 0; x < size; x++) {
  71030. for (var y = 0; y < size; y++) {
  71031. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  71032. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  71033. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  71034. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71035. context.fillRect(x, y, 1, 1);
  71036. }
  71037. }
  71038. this._randomTexture.update(false);
  71039. };
  71040. __decorate([
  71041. BABYLON.serialize()
  71042. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  71043. __decorate([
  71044. BABYLON.serialize()
  71045. ], SSAORenderingPipeline.prototype, "radius", void 0);
  71046. __decorate([
  71047. BABYLON.serialize()
  71048. ], SSAORenderingPipeline.prototype, "area", void 0);
  71049. __decorate([
  71050. BABYLON.serialize()
  71051. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  71052. __decorate([
  71053. BABYLON.serialize()
  71054. ], SSAORenderingPipeline.prototype, "base", void 0);
  71055. return SSAORenderingPipeline;
  71056. }(BABYLON.PostProcessRenderPipeline));
  71057. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  71058. })(BABYLON || (BABYLON = {}));
  71059. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  71060. "use strict";
  71061. var BABYLON;
  71062. (function (BABYLON) {
  71063. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  71064. __extends(SSAO2RenderingPipeline, _super);
  71065. /**
  71066. * @constructor
  71067. * @param {string} name - The rendering pipeline name
  71068. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71069. * @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 }
  71070. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71071. */
  71072. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  71073. var _this = _super.call(this, scene.getEngine(), name) || this;
  71074. // Members
  71075. /**
  71076. * The PassPostProcess id in the pipeline that contains the original scene color
  71077. */
  71078. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71079. /**
  71080. * The SSAO PostProcess id in the pipeline
  71081. */
  71082. _this.SSAORenderEffect = "SSAORenderEffect";
  71083. /**
  71084. * The horizontal blur PostProcess id in the pipeline
  71085. */
  71086. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71087. /**
  71088. * The vertical blur PostProcess id in the pipeline
  71089. */
  71090. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71091. /**
  71092. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71093. */
  71094. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71095. /**
  71096. * The output strength of the SSAO post-process. Default value is 1.0.
  71097. */
  71098. _this.totalStrength = 1.0;
  71099. /**
  71100. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71101. */
  71102. _this.maxZ = 100.0;
  71103. /**
  71104. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  71105. */
  71106. _this.minZAspect = 0.2;
  71107. /**
  71108. * Number of samples used for the SSAO calculations. Default value is 8
  71109. */
  71110. _this._samples = 8;
  71111. /**
  71112. * Are we using bilateral blur ?
  71113. */
  71114. _this._expensiveBlur = true;
  71115. /**
  71116. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71117. */
  71118. _this.radius = 2.0;
  71119. /**
  71120. * The base color of the SSAO post-process
  71121. * The final result is "base + ssao" between [0, 1]
  71122. */
  71123. _this.base = 0.1;
  71124. _this._firstUpdate = true;
  71125. _this._scene = scene;
  71126. if (!_this.isSupported) {
  71127. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71128. return _this;
  71129. }
  71130. var ssaoRatio = ratio.ssaoRatio || ratio;
  71131. var blurRatio = ratio.blurRatio || ratio;
  71132. // Set up assets
  71133. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71134. _this._createRandomTexture();
  71135. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71136. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71137. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71138. _this._createSSAOPostProcess(1.0);
  71139. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71140. _this._createSSAOCombinePostProcess(blurRatio);
  71141. // Set up pipeline
  71142. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71143. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71144. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71145. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71147. // Finish
  71148. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71149. if (cameras)
  71150. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71151. return _this;
  71152. }
  71153. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71154. get: function () {
  71155. return this._samples;
  71156. },
  71157. set: function (n) {
  71158. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71159. this._samples = n;
  71160. this._sampleSphere = this._generateHemisphere();
  71161. this._firstUpdate = true;
  71162. },
  71163. enumerable: true,
  71164. configurable: true
  71165. });
  71166. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71167. get: function () {
  71168. return this._expensiveBlur;
  71169. },
  71170. set: function (b) {
  71171. 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"]);
  71172. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71173. this._expensiveBlur = b;
  71174. this._firstUpdate = true;
  71175. },
  71176. enumerable: true,
  71177. configurable: true
  71178. });
  71179. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71180. /**
  71181. * Support test.
  71182. */
  71183. get: function () {
  71184. var engine = BABYLON.Engine.LastCreatedEngine;
  71185. if (!engine) {
  71186. return false;
  71187. }
  71188. return engine.getCaps().drawBuffersExtension;
  71189. },
  71190. enumerable: true,
  71191. configurable: true
  71192. });
  71193. // Public Methods
  71194. /**
  71195. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71196. */
  71197. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71198. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71199. for (var i = 0; i < this._scene.cameras.length; i++) {
  71200. var camera = this._scene.cameras[i];
  71201. this._originalColorPostProcess.dispose(camera);
  71202. this._ssaoPostProcess.dispose(camera);
  71203. this._blurHPostProcess.dispose(camera);
  71204. this._blurVPostProcess.dispose(camera);
  71205. this._ssaoCombinePostProcess.dispose(camera);
  71206. }
  71207. this._randomTexture.dispose();
  71208. if (disableGeometryBufferRenderer)
  71209. this._scene.disableGeometryBufferRenderer();
  71210. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71211. _super.prototype.dispose.call(this);
  71212. };
  71213. // Private Methods
  71214. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  71215. var _this = this;
  71216. this._samplerOffsets = [];
  71217. var expensive = this.expensiveBlur;
  71218. for (var i = -8; i < 8; i++) {
  71219. this._samplerOffsets.push(i * 2 + 0.5);
  71220. }
  71221. 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");
  71222. this._blurHPostProcess.onApply = function (effect) {
  71223. if (!_this._scene.activeCamera) {
  71224. return;
  71225. }
  71226. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  71227. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71228. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71229. effect.setFloat("radius", _this.radius);
  71230. effect.setTexture("depthSampler", _this._depthTexture);
  71231. if (_this._firstUpdate) {
  71232. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71233. }
  71234. };
  71235. 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");
  71236. this._blurVPostProcess.onApply = function (effect) {
  71237. if (!_this._scene.activeCamera) {
  71238. return;
  71239. }
  71240. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  71241. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71242. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71243. effect.setFloat("radius", _this.radius);
  71244. effect.setTexture("depthSampler", _this._depthTexture);
  71245. if (_this._firstUpdate) {
  71246. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71247. _this._firstUpdate = false;
  71248. }
  71249. };
  71250. };
  71251. SSAO2RenderingPipeline.prototype._rebuild = function () {
  71252. this._firstUpdate = true;
  71253. _super.prototype._rebuild.call(this);
  71254. };
  71255. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  71256. var numSamples = this.samples;
  71257. var result = [];
  71258. var vector, scale;
  71259. var rand = function (min, max) {
  71260. return Math.random() * (max - min) + min;
  71261. };
  71262. var i = 0;
  71263. while (i < numSamples) {
  71264. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  71265. vector.normalize();
  71266. scale = i / numSamples;
  71267. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  71268. vector.scaleInPlace(scale);
  71269. result.push(vector.x, vector.y, vector.z);
  71270. i++;
  71271. }
  71272. return result;
  71273. };
  71274. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71275. var _this = this;
  71276. var numSamples = this.samples;
  71277. this._sampleSphere = this._generateHemisphere();
  71278. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  71279. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71280. "base", "range", "projection", "near", "far", "texelSize",
  71281. "xViewport", "yViewport", "maxZ", "minZAspect"
  71282. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71283. this._ssaoPostProcess.onApply = function (effect) {
  71284. if (_this._firstUpdate) {
  71285. effect.setArray3("sampleSphere", _this._sampleSphere);
  71286. effect.setFloat("randTextureTiles", 4.0);
  71287. }
  71288. if (!_this._scene.activeCamera) {
  71289. return;
  71290. }
  71291. effect.setFloat("samplesFactor", 1 / _this.samples);
  71292. effect.setFloat("totalStrength", _this.totalStrength);
  71293. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  71294. effect.setFloat("radius", _this.radius);
  71295. effect.setFloat("maxZ", _this.maxZ);
  71296. effect.setFloat("minZAspect", _this.minZAspect);
  71297. effect.setFloat("base", _this.base);
  71298. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71299. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71300. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  71301. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  71302. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  71303. effect.setTexture("textureSampler", _this._depthTexture);
  71304. effect.setTexture("normalSampler", _this._normalTexture);
  71305. effect.setTexture("randomSampler", _this._randomTexture);
  71306. };
  71307. };
  71308. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71309. var _this = this;
  71310. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71311. this._ssaoCombinePostProcess.onApply = function (effect) {
  71312. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71313. };
  71314. };
  71315. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  71316. var size = 512;
  71317. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71318. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71319. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71320. var context = this._randomTexture.getContext();
  71321. var rand = function (min, max) {
  71322. return Math.random() * (max - min) + min;
  71323. };
  71324. var randVector = BABYLON.Vector3.Zero();
  71325. for (var x = 0; x < size; x++) {
  71326. for (var y = 0; y < size; y++) {
  71327. randVector.x = rand(0.0, 1.0);
  71328. randVector.y = rand(0.0, 1.0);
  71329. randVector.z = 0.0;
  71330. randVector.normalize();
  71331. randVector.scaleInPlace(255);
  71332. randVector.x = Math.floor(randVector.x);
  71333. randVector.y = Math.floor(randVector.y);
  71334. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71335. context.fillRect(x, y, 1, 1);
  71336. }
  71337. }
  71338. this._randomTexture.update(false);
  71339. };
  71340. __decorate([
  71341. BABYLON.serialize()
  71342. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  71343. __decorate([
  71344. BABYLON.serialize()
  71345. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  71346. __decorate([
  71347. BABYLON.serialize()
  71348. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  71349. __decorate([
  71350. BABYLON.serialize("samples")
  71351. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  71352. __decorate([
  71353. BABYLON.serialize("expensiveBlur")
  71354. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  71355. __decorate([
  71356. BABYLON.serialize()
  71357. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  71358. __decorate([
  71359. BABYLON.serialize()
  71360. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  71361. return SSAO2RenderingPipeline;
  71362. }(BABYLON.PostProcessRenderPipeline));
  71363. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  71364. })(BABYLON || (BABYLON = {}));
  71365. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  71366. "use strict";
  71367. // BABYLON.JS Chromatic Aberration GLSL Shader
  71368. // Author: Olivier Guyot
  71369. // Separates very slightly R, G and B colors on the edges of the screen
  71370. // Inspired by Francois Tarlier & Martins Upitis
  71371. var BABYLON;
  71372. (function (BABYLON) {
  71373. var LensRenderingPipeline = /** @class */ (function (_super) {
  71374. __extends(LensRenderingPipeline, _super);
  71375. /**
  71376. * @constructor
  71377. *
  71378. * Effect parameters are as follow:
  71379. * {
  71380. * chromatic_aberration: number; // from 0 to x (1 for realism)
  71381. * edge_blur: number; // from 0 to x (1 for realism)
  71382. * distortion: number; // from 0 to x (1 for realism)
  71383. * grain_amount: number; // from 0 to 1
  71384. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  71385. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  71386. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  71387. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  71388. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  71389. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  71390. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  71391. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  71392. * }
  71393. * Note: if an effect parameter is unset, effect is disabled
  71394. *
  71395. * @param {string} name - The rendering pipeline name
  71396. * @param {object} parameters - An object containing all parameters (see above)
  71397. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71398. * @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)
  71399. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71400. */
  71401. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  71402. if (ratio === void 0) { ratio = 1.0; }
  71403. var _this = _super.call(this, scene.getEngine(), name) || this;
  71404. // Lens effects can be of the following:
  71405. // - chromatic aberration (slight shift of RGB colors)
  71406. // - blur on the edge of the lens
  71407. // - lens distortion
  71408. // - depth-of-field blur & highlights enhancing
  71409. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  71410. // - grain effect (noise or custom texture)
  71411. // Two additional texture samplers are needed:
  71412. // - depth map (for depth-of-field)
  71413. // - grain texture
  71414. /**
  71415. * The chromatic aberration PostProcess id in the pipeline
  71416. */
  71417. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  71418. /**
  71419. * The highlights enhancing PostProcess id in the pipeline
  71420. */
  71421. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  71422. /**
  71423. * The depth-of-field PostProcess id in the pipeline
  71424. */
  71425. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  71426. _this._scene = scene;
  71427. // Fetch texture samplers
  71428. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71429. if (parameters.grain_texture) {
  71430. _this._grainTexture = parameters.grain_texture;
  71431. }
  71432. else {
  71433. _this._createGrainTexture();
  71434. }
  71435. // save parameters
  71436. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  71437. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  71438. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  71439. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  71440. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  71441. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  71442. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  71443. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  71444. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  71445. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  71446. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  71447. // Create effects
  71448. _this._createChromaticAberrationPostProcess(ratio);
  71449. _this._createHighlightsPostProcess(ratio);
  71450. _this._createDepthOfFieldPostProcess(ratio / 4);
  71451. // Set up pipeline
  71452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  71453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  71454. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  71455. if (_this._highlightsGain === -1) {
  71456. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  71457. }
  71458. // Finish
  71459. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71460. if (cameras) {
  71461. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71462. }
  71463. return _this;
  71464. }
  71465. // public methods (self explanatory)
  71466. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  71467. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  71468. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  71469. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  71470. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  71471. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  71472. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  71473. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  71474. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  71475. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  71476. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  71477. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  71478. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  71479. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  71480. };
  71481. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  71482. this._highlightsPostProcess.updateEffect();
  71483. };
  71484. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  71485. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  71486. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  71487. this._highlightsGain = amount;
  71488. };
  71489. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  71490. if (this._highlightsGain === -1) {
  71491. this._highlightsGain = 1.0;
  71492. }
  71493. this._highlightsThreshold = amount;
  71494. };
  71495. LensRenderingPipeline.prototype.disableHighlights = function () {
  71496. this._highlightsGain = -1;
  71497. };
  71498. /**
  71499. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  71500. */
  71501. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71502. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71503. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71504. this._chromaticAberrationPostProcess = null;
  71505. this._highlightsPostProcess = null;
  71506. this._depthOfFieldPostProcess = null;
  71507. this._grainTexture.dispose();
  71508. if (disableDepthRender)
  71509. this._scene.disableDepthRenderer();
  71510. };
  71511. // colors shifting and distortion
  71512. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  71513. var _this = this;
  71514. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  71515. [], // samplers
  71516. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71517. this._chromaticAberrationPostProcess.onApply = function (effect) {
  71518. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  71519. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71520. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71521. effect.setFloat('radialIntensity', 1);
  71522. effect.setFloat2('direction', 17, 17);
  71523. effect.setFloat2('centerPosition', 0.5, 0.5);
  71524. };
  71525. };
  71526. // highlights enhancing
  71527. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  71528. var _this = this;
  71529. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  71530. [], // samplers
  71531. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  71532. this._highlightsPostProcess.onApply = function (effect) {
  71533. effect.setFloat('gain', _this._highlightsGain);
  71534. effect.setFloat('threshold', _this._highlightsThreshold);
  71535. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  71536. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71537. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71538. };
  71539. };
  71540. // colors shifting and distortion
  71541. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  71542. var _this = this;
  71543. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  71544. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  71545. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  71546. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71547. this._depthOfFieldPostProcess.onApply = function (effect) {
  71548. effect.setTexture("depthSampler", _this._depthTexture);
  71549. effect.setTexture("grainSampler", _this._grainTexture);
  71550. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  71551. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  71552. effect.setFloat('grain_amount', _this._grainAmount);
  71553. effect.setBool('blur_noise', _this._blurNoise);
  71554. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71555. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71556. effect.setFloat('distortion', _this._distortion);
  71557. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  71558. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  71559. effect.setFloat('aperture', _this._dofAperture);
  71560. effect.setFloat('darken', _this._dofDarken);
  71561. effect.setFloat('edge_blur', _this._edgeBlur);
  71562. effect.setBool('highlights', (_this._highlightsGain !== -1));
  71563. if (_this._scene.activeCamera) {
  71564. effect.setFloat('near', _this._scene.activeCamera.minZ);
  71565. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  71566. }
  71567. };
  71568. };
  71569. // creates a black and white random noise texture, 512x512
  71570. LensRenderingPipeline.prototype._createGrainTexture = function () {
  71571. var size = 512;
  71572. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71573. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71574. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71575. var context = this._grainTexture.getContext();
  71576. var rand = function (min, max) {
  71577. return Math.random() * (max - min) + min;
  71578. };
  71579. var value;
  71580. for (var x = 0; x < size; x++) {
  71581. for (var y = 0; y < size; y++) {
  71582. value = Math.floor(rand(0.42, 0.58) * 255);
  71583. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  71584. context.fillRect(x, y, 1, 1);
  71585. }
  71586. }
  71587. this._grainTexture.update(false);
  71588. };
  71589. return LensRenderingPipeline;
  71590. }(BABYLON.PostProcessRenderPipeline));
  71591. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  71592. })(BABYLON || (BABYLON = {}));
  71593. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  71594. "use strict";
  71595. var BABYLON;
  71596. (function (BABYLON) {
  71597. var StandardRenderingPipeline = /** @class */ (function (_super) {
  71598. __extends(StandardRenderingPipeline, _super);
  71599. /**
  71600. * @constructor
  71601. * @param {string} name - The rendering pipeline name
  71602. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71603. * @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)
  71604. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  71605. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71606. */
  71607. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  71608. if (originalPostProcess === void 0) { originalPostProcess = null; }
  71609. var _this = _super.call(this, scene.getEngine(), name) || this;
  71610. _this.downSampleX4PostProcess = null;
  71611. _this.brightPassPostProcess = null;
  71612. _this.blurHPostProcesses = [];
  71613. _this.blurVPostProcesses = [];
  71614. _this.textureAdderPostProcess = null;
  71615. _this.volumetricLightPostProcess = null;
  71616. _this.volumetricLightSmoothXPostProcess = null;
  71617. _this.volumetricLightSmoothYPostProcess = null;
  71618. _this.volumetricLightMergePostProces = null;
  71619. _this.volumetricLightFinalPostProcess = null;
  71620. _this.luminancePostProcess = null;
  71621. _this.luminanceDownSamplePostProcesses = [];
  71622. _this.hdrPostProcess = null;
  71623. _this.textureAdderFinalPostProcess = null;
  71624. _this.lensFlareFinalPostProcess = null;
  71625. _this.hdrFinalPostProcess = null;
  71626. _this.lensFlarePostProcess = null;
  71627. _this.lensFlareComposePostProcess = null;
  71628. _this.motionBlurPostProcess = null;
  71629. _this.depthOfFieldPostProcess = null;
  71630. // Values
  71631. _this.brightThreshold = 1.0;
  71632. _this.blurWidth = 512.0;
  71633. _this.horizontalBlur = false;
  71634. _this.exposure = 1.0;
  71635. _this.lensTexture = null;
  71636. _this.volumetricLightCoefficient = 0.2;
  71637. _this.volumetricLightPower = 4.0;
  71638. _this.volumetricLightBlurScale = 64.0;
  71639. _this.sourceLight = null;
  71640. _this.hdrMinimumLuminance = 1.0;
  71641. _this.hdrDecreaseRate = 0.5;
  71642. _this.hdrIncreaseRate = 0.5;
  71643. _this.lensColorTexture = null;
  71644. _this.lensFlareStrength = 20.0;
  71645. _this.lensFlareGhostDispersal = 1.4;
  71646. _this.lensFlareHaloWidth = 0.7;
  71647. _this.lensFlareDistortionStrength = 16.0;
  71648. _this.lensStarTexture = null;
  71649. _this.lensFlareDirtTexture = null;
  71650. _this.depthOfFieldDistance = 10.0;
  71651. _this.depthOfFieldBlurWidth = 64.0;
  71652. _this.motionStrength = 1.0;
  71653. // IAnimatable
  71654. _this.animations = [];
  71655. _this._currentDepthOfFieldSource = null;
  71656. _this._hdrCurrentLuminance = 1.0;
  71657. // Getters and setters
  71658. _this._bloomEnabled = true;
  71659. _this._depthOfFieldEnabled = false;
  71660. _this._vlsEnabled = false;
  71661. _this._lensFlareEnabled = false;
  71662. _this._hdrEnabled = false;
  71663. _this._motionBlurEnabled = false;
  71664. _this._motionBlurSamples = 64.0;
  71665. _this._volumetricLightStepsCount = 50.0;
  71666. _this._cameras = cameras || [];
  71667. // Initialize
  71668. _this._scene = scene;
  71669. _this._basePostProcess = originalPostProcess;
  71670. _this._ratio = ratio;
  71671. // Misc
  71672. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71673. // Finish
  71674. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71675. _this._buildPipeline();
  71676. return _this;
  71677. }
  71678. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  71679. get: function () {
  71680. return this._bloomEnabled;
  71681. },
  71682. set: function (enabled) {
  71683. if (this._bloomEnabled === enabled) {
  71684. return;
  71685. }
  71686. this._bloomEnabled = enabled;
  71687. this._buildPipeline();
  71688. },
  71689. enumerable: true,
  71690. configurable: true
  71691. });
  71692. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  71693. get: function () {
  71694. return this._depthOfFieldEnabled;
  71695. },
  71696. set: function (enabled) {
  71697. if (this._depthOfFieldEnabled === enabled) {
  71698. return;
  71699. }
  71700. this._depthOfFieldEnabled = enabled;
  71701. this._buildPipeline();
  71702. },
  71703. enumerable: true,
  71704. configurable: true
  71705. });
  71706. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  71707. get: function () {
  71708. return this._lensFlareEnabled;
  71709. },
  71710. set: function (enabled) {
  71711. if (this._lensFlareEnabled === enabled) {
  71712. return;
  71713. }
  71714. this._lensFlareEnabled = enabled;
  71715. this._buildPipeline();
  71716. },
  71717. enumerable: true,
  71718. configurable: true
  71719. });
  71720. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  71721. get: function () {
  71722. return this._hdrEnabled;
  71723. },
  71724. set: function (enabled) {
  71725. if (this._hdrEnabled === enabled) {
  71726. return;
  71727. }
  71728. this._hdrEnabled = enabled;
  71729. this._buildPipeline();
  71730. },
  71731. enumerable: true,
  71732. configurable: true
  71733. });
  71734. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  71735. get: function () {
  71736. return this._vlsEnabled;
  71737. },
  71738. set: function (enabled) {
  71739. if (this._vlsEnabled === enabled) {
  71740. return;
  71741. }
  71742. if (enabled) {
  71743. var geometry = this._scene.enableGeometryBufferRenderer();
  71744. if (!geometry) {
  71745. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  71746. return;
  71747. }
  71748. }
  71749. this._vlsEnabled = enabled;
  71750. this._buildPipeline();
  71751. },
  71752. enumerable: true,
  71753. configurable: true
  71754. });
  71755. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  71756. get: function () {
  71757. return this._motionBlurEnabled;
  71758. },
  71759. set: function (enabled) {
  71760. if (this._motionBlurEnabled === enabled) {
  71761. return;
  71762. }
  71763. this._motionBlurEnabled = enabled;
  71764. this._buildPipeline();
  71765. },
  71766. enumerable: true,
  71767. configurable: true
  71768. });
  71769. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  71770. get: function () {
  71771. return this._volumetricLightStepsCount;
  71772. },
  71773. set: function (count) {
  71774. if (this.volumetricLightPostProcess) {
  71775. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  71776. }
  71777. this._volumetricLightStepsCount = count;
  71778. },
  71779. enumerable: true,
  71780. configurable: true
  71781. });
  71782. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  71783. get: function () {
  71784. return this._motionBlurSamples;
  71785. },
  71786. set: function (samples) {
  71787. if (this.motionBlurPostProcess) {
  71788. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  71789. }
  71790. this._motionBlurSamples = samples;
  71791. },
  71792. enumerable: true,
  71793. configurable: true
  71794. });
  71795. StandardRenderingPipeline.prototype._buildPipeline = function () {
  71796. var _this = this;
  71797. var ratio = this._ratio;
  71798. var scene = this._scene;
  71799. this._disposePostProcesses();
  71800. this._reset();
  71801. // Create pass post-process
  71802. if (!this._basePostProcess) {
  71803. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  71804. this.originalPostProcess.onApply = function (effect) {
  71805. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  71806. };
  71807. }
  71808. else {
  71809. this.originalPostProcess = this._basePostProcess;
  71810. }
  71811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  71812. this._currentDepthOfFieldSource = this.originalPostProcess;
  71813. if (this._vlsEnabled) {
  71814. // Create volumetric light
  71815. this._createVolumetricLightPostProcess(scene, ratio);
  71816. // Create volumetric light final post-process
  71817. 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);
  71818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  71819. }
  71820. if (this._bloomEnabled) {
  71821. // Create down sample X4 post-process
  71822. this._createDownSampleX4PostProcess(scene, ratio / 2);
  71823. // Create bright pass post-process
  71824. this._createBrightPassPostProcess(scene, ratio / 2);
  71825. // Create gaussian blur post-processes (down sampling blurs)
  71826. this._createBlurPostProcesses(scene, ratio / 4, 1);
  71827. // Create texture adder post-process
  71828. this._createTextureAdderPostProcess(scene, ratio);
  71829. // Create depth-of-field source post-process
  71830. 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);
  71831. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  71832. }
  71833. if (this._lensFlareEnabled) {
  71834. // Create lens flare post-process
  71835. this._createLensFlarePostProcess(scene, ratio);
  71836. // Create depth-of-field source post-process post lens-flare and disable it now
  71837. 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);
  71838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  71839. }
  71840. if (this._hdrEnabled) {
  71841. // Create luminance
  71842. this._createLuminancePostProcesses(scene, this._floatTextureType);
  71843. // Create HDR
  71844. this._createHdrPostProcess(scene, ratio);
  71845. // Create depth-of-field source post-process post hdr and disable it now
  71846. 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);
  71847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  71848. }
  71849. if (this._depthOfFieldEnabled) {
  71850. // Create gaussian blur used by depth-of-field
  71851. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  71852. // Create depth-of-field post-process
  71853. this._createDepthOfFieldPostProcess(scene, ratio);
  71854. }
  71855. if (this._motionBlurEnabled) {
  71856. // Create motion blur post-process
  71857. this._createMotionBlurPostProcess(scene, ratio);
  71858. }
  71859. if (this._cameras !== null) {
  71860. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71861. }
  71862. };
  71863. // Down Sample X4 Post-Processs
  71864. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  71865. var _this = this;
  71866. var downSampleX4Offsets = new Array(32);
  71867. 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);
  71868. this.downSampleX4PostProcess.onApply = function (effect) {
  71869. var id = 0;
  71870. var width = _this.downSampleX4PostProcess.width;
  71871. var height = _this.downSampleX4PostProcess.height;
  71872. for (var i = -2; i < 2; i++) {
  71873. for (var j = -2; j < 2; j++) {
  71874. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  71875. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  71876. id += 2;
  71877. }
  71878. }
  71879. effect.setArray2("dsOffsets", downSampleX4Offsets);
  71880. };
  71881. // Add to pipeline
  71882. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  71883. };
  71884. // Brightpass Post-Process
  71885. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  71886. var _this = this;
  71887. var brightOffsets = new Array(8);
  71888. 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);
  71889. this.brightPassPostProcess.onApply = function (effect) {
  71890. var sU = (1.0 / _this.brightPassPostProcess.width);
  71891. var sV = (1.0 / _this.brightPassPostProcess.height);
  71892. brightOffsets[0] = -0.5 * sU;
  71893. brightOffsets[1] = 0.5 * sV;
  71894. brightOffsets[2] = 0.5 * sU;
  71895. brightOffsets[3] = 0.5 * sV;
  71896. brightOffsets[4] = -0.5 * sU;
  71897. brightOffsets[5] = -0.5 * sV;
  71898. brightOffsets[6] = 0.5 * sU;
  71899. brightOffsets[7] = -0.5 * sV;
  71900. effect.setArray2("dsOffsets", brightOffsets);
  71901. effect.setFloat("brightThreshold", _this.brightThreshold);
  71902. };
  71903. // Add to pipeline
  71904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  71905. };
  71906. // Create blur H&V post-processes
  71907. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  71908. var _this = this;
  71909. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  71910. var engine = scene.getEngine();
  71911. 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);
  71912. 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);
  71913. blurX.onActivateObservable.add(function () {
  71914. var dw = blurX.width / engine.getRenderWidth();
  71915. blurX.kernel = _this[blurWidthKey] * dw;
  71916. });
  71917. blurY.onActivateObservable.add(function () {
  71918. var dw = blurY.height / engine.getRenderHeight();
  71919. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  71920. });
  71921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  71922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  71923. this.blurHPostProcesses.push(blurX);
  71924. this.blurVPostProcesses.push(blurY);
  71925. };
  71926. // Create texture adder post-process
  71927. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  71928. var _this = this;
  71929. 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);
  71930. this.textureAdderPostProcess.onApply = function (effect) {
  71931. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  71932. effect.setTexture("lensSampler", _this.lensTexture);
  71933. effect.setFloat("exposure", _this.exposure);
  71934. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  71935. };
  71936. // Add to pipeline
  71937. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  71938. };
  71939. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  71940. var _this = this;
  71941. var geometryRenderer = scene.enableGeometryBufferRenderer();
  71942. geometryRenderer.enablePosition = true;
  71943. var geometry = geometryRenderer.getGBuffer();
  71944. // Base post-process
  71945. 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));
  71946. var depthValues = BABYLON.Vector2.Zero();
  71947. this.volumetricLightPostProcess.onApply = function (effect) {
  71948. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  71949. var generator = _this.sourceLight.getShadowGenerator();
  71950. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  71951. effect.setTexture("positionSampler", geometry.textures[2]);
  71952. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  71953. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  71954. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  71955. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  71956. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  71957. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  71958. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  71959. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  71960. effect.setVector2("depthValues", depthValues);
  71961. }
  71962. };
  71963. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  71964. // Smooth
  71965. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  71966. // Merge
  71967. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  71968. this.volumetricLightMergePostProces.onApply = function (effect) {
  71969. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  71970. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  71971. };
  71972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  71973. };
  71974. // Create luminance
  71975. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  71976. var _this = this;
  71977. // Create luminance
  71978. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  71979. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  71980. var offsets = [];
  71981. this.luminancePostProcess.onApply = function (effect) {
  71982. var sU = (1.0 / _this.luminancePostProcess.width);
  71983. var sV = (1.0 / _this.luminancePostProcess.height);
  71984. offsets[0] = -0.5 * sU;
  71985. offsets[1] = 0.5 * sV;
  71986. offsets[2] = 0.5 * sU;
  71987. offsets[3] = 0.5 * sV;
  71988. offsets[4] = -0.5 * sU;
  71989. offsets[5] = -0.5 * sV;
  71990. offsets[6] = 0.5 * sU;
  71991. offsets[7] = -0.5 * sV;
  71992. effect.setArray2("lumOffsets", offsets);
  71993. };
  71994. // Add to pipeline
  71995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  71996. // Create down sample luminance
  71997. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  71998. var size = Math.pow(3, i);
  71999. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72000. if (i === 0) {
  72001. defines += "#define FINAL_DOWN_SAMPLER";
  72002. }
  72003. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72004. this.luminanceDownSamplePostProcesses.push(postProcess);
  72005. }
  72006. // Create callbacks and add effects
  72007. var lastLuminance = this.luminancePostProcess;
  72008. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72009. var downSampleOffsets = new Array(18);
  72010. pp.onApply = function (effect) {
  72011. if (!lastLuminance) {
  72012. return;
  72013. }
  72014. var id = 0;
  72015. for (var x = -1; x < 2; x++) {
  72016. for (var y = -1; y < 2; y++) {
  72017. downSampleOffsets[id] = x / lastLuminance.width;
  72018. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72019. id += 2;
  72020. }
  72021. }
  72022. effect.setArray2("dsOffsets", downSampleOffsets);
  72023. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72024. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72025. lastLuminance = _this.luminancePostProcess;
  72026. }
  72027. else {
  72028. lastLuminance = pp;
  72029. }
  72030. };
  72031. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72032. pp.onAfterRender = function (effect) {
  72033. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  72034. 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);
  72035. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  72036. };
  72037. }
  72038. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  72039. });
  72040. };
  72041. // Create HDR post-process
  72042. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  72043. var _this = this;
  72044. 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);
  72045. var outputLiminance = 1;
  72046. var time = 0;
  72047. var lastTime = 0;
  72048. this.hdrPostProcess.onApply = function (effect) {
  72049. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  72050. time += scene.getEngine().getDeltaTime();
  72051. if (outputLiminance < 0) {
  72052. outputLiminance = _this._hdrCurrentLuminance;
  72053. }
  72054. else {
  72055. var dt = (lastTime - time) / 1000.0;
  72056. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  72057. outputLiminance += _this.hdrDecreaseRate * dt;
  72058. }
  72059. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  72060. outputLiminance -= _this.hdrIncreaseRate * dt;
  72061. }
  72062. else {
  72063. outputLiminance = _this._hdrCurrentLuminance;
  72064. }
  72065. }
  72066. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  72067. effect.setFloat("averageLuminance", outputLiminance);
  72068. lastTime = time;
  72069. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  72070. };
  72071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  72072. };
  72073. // Create lens flare post-process
  72074. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  72075. var _this = this;
  72076. 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);
  72077. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  72078. this._createBlurPostProcesses(scene, ratio / 4, 2);
  72079. 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);
  72080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72081. var resolution = new BABYLON.Vector2(0, 0);
  72082. // Lens flare
  72083. this.lensFlarePostProcess.onApply = function (effect) {
  72084. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72085. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72086. effect.setFloat("strength", _this.lensFlareStrength);
  72087. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72088. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72089. // Shift
  72090. resolution.x = _this.lensFlarePostProcess.width;
  72091. resolution.y = _this.lensFlarePostProcess.height;
  72092. effect.setVector2("resolution", resolution);
  72093. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72094. };
  72095. // Compose
  72096. 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);
  72097. 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);
  72098. this.lensFlareComposePostProcess.onApply = function (effect) {
  72099. if (!_this._scene.activeCamera) {
  72100. return;
  72101. }
  72102. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72103. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72104. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  72105. // Lens start rotation matrix
  72106. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  72107. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72108. 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));
  72109. camRot *= 4.0;
  72110. 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);
  72111. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72112. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72113. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72114. };
  72115. };
  72116. // Create depth-of-field post-process
  72117. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72118. var _this = this;
  72119. 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);
  72120. this.depthOfFieldPostProcess.onApply = function (effect) {
  72121. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72122. effect.setTexture("depthSampler", _this._getDepthTexture());
  72123. effect.setFloat("distance", _this.depthOfFieldDistance);
  72124. };
  72125. // Add to pipeline
  72126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72127. };
  72128. // Create motion blur post-process
  72129. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72130. var _this = this;
  72131. 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);
  72132. var motionScale = 0;
  72133. var prevViewProjection = BABYLON.Matrix.Identity();
  72134. var invViewProjection = BABYLON.Matrix.Identity();
  72135. var viewProjection = BABYLON.Matrix.Identity();
  72136. var screenSize = BABYLON.Vector2.Zero();
  72137. this.motionBlurPostProcess.onApply = function (effect) {
  72138. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72139. viewProjection.invertToRef(invViewProjection);
  72140. effect.setMatrix("inverseViewProjection", invViewProjection);
  72141. effect.setMatrix("prevViewProjection", prevViewProjection);
  72142. prevViewProjection = viewProjection;
  72143. screenSize.x = _this.motionBlurPostProcess.width;
  72144. screenSize.y = _this.motionBlurPostProcess.height;
  72145. effect.setVector2("screenSize", screenSize);
  72146. motionScale = scene.getEngine().getFps() / 60.0;
  72147. effect.setFloat("motionScale", motionScale);
  72148. effect.setFloat("motionStrength", _this.motionStrength);
  72149. effect.setTexture("depthSampler", _this._getDepthTexture());
  72150. };
  72151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72152. };
  72153. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72154. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72155. var renderer = this._scene.enableGeometryBufferRenderer();
  72156. return renderer.getGBuffer().textures[0];
  72157. }
  72158. return this._scene.enableDepthRenderer().getDepthMap();
  72159. };
  72160. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72161. for (var i = 0; i < this._cameras.length; i++) {
  72162. var camera = this._cameras[i];
  72163. if (this.originalPostProcess) {
  72164. this.originalPostProcess.dispose(camera);
  72165. }
  72166. if (this.downSampleX4PostProcess) {
  72167. this.downSampleX4PostProcess.dispose(camera);
  72168. }
  72169. if (this.brightPassPostProcess) {
  72170. this.brightPassPostProcess.dispose(camera);
  72171. }
  72172. if (this.textureAdderPostProcess) {
  72173. this.textureAdderPostProcess.dispose(camera);
  72174. }
  72175. if (this.textureAdderFinalPostProcess) {
  72176. this.textureAdderFinalPostProcess.dispose(camera);
  72177. }
  72178. if (this.volumetricLightPostProcess) {
  72179. this.volumetricLightPostProcess.dispose(camera);
  72180. }
  72181. if (this.volumetricLightSmoothXPostProcess) {
  72182. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72183. }
  72184. if (this.volumetricLightSmoothYPostProcess) {
  72185. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72186. }
  72187. if (this.volumetricLightMergePostProces) {
  72188. this.volumetricLightMergePostProces.dispose(camera);
  72189. }
  72190. if (this.volumetricLightFinalPostProcess) {
  72191. this.volumetricLightFinalPostProcess.dispose(camera);
  72192. }
  72193. if (this.lensFlarePostProcess) {
  72194. this.lensFlarePostProcess.dispose(camera);
  72195. }
  72196. if (this.lensFlareComposePostProcess) {
  72197. this.lensFlareComposePostProcess.dispose(camera);
  72198. }
  72199. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72200. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72201. }
  72202. if (this.luminancePostProcess) {
  72203. this.luminancePostProcess.dispose(camera);
  72204. }
  72205. if (this.hdrPostProcess) {
  72206. this.hdrPostProcess.dispose(camera);
  72207. }
  72208. if (this.hdrFinalPostProcess) {
  72209. this.hdrFinalPostProcess.dispose(camera);
  72210. }
  72211. if (this.depthOfFieldPostProcess) {
  72212. this.depthOfFieldPostProcess.dispose(camera);
  72213. }
  72214. if (this.motionBlurPostProcess) {
  72215. this.motionBlurPostProcess.dispose(camera);
  72216. }
  72217. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  72218. this.blurHPostProcesses[j].dispose(camera);
  72219. }
  72220. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  72221. this.blurVPostProcesses[j].dispose(camera);
  72222. }
  72223. }
  72224. this.originalPostProcess = null;
  72225. this.downSampleX4PostProcess = null;
  72226. this.brightPassPostProcess = null;
  72227. this.textureAdderPostProcess = null;
  72228. this.textureAdderFinalPostProcess = null;
  72229. this.volumetricLightPostProcess = null;
  72230. this.volumetricLightSmoothXPostProcess = null;
  72231. this.volumetricLightSmoothYPostProcess = null;
  72232. this.volumetricLightMergePostProces = null;
  72233. this.volumetricLightFinalPostProcess = null;
  72234. this.lensFlarePostProcess = null;
  72235. this.lensFlareComposePostProcess = null;
  72236. this.luminancePostProcess = null;
  72237. this.hdrPostProcess = null;
  72238. this.hdrFinalPostProcess = null;
  72239. this.depthOfFieldPostProcess = null;
  72240. this.motionBlurPostProcess = null;
  72241. this.luminanceDownSamplePostProcesses = [];
  72242. this.blurHPostProcesses = [];
  72243. this.blurVPostProcesses = [];
  72244. };
  72245. // Dispose
  72246. StandardRenderingPipeline.prototype.dispose = function () {
  72247. this._disposePostProcesses();
  72248. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72249. _super.prototype.dispose.call(this);
  72250. };
  72251. // Serialize rendering pipeline
  72252. StandardRenderingPipeline.prototype.serialize = function () {
  72253. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72254. serializationObject.customType = "StandardRenderingPipeline";
  72255. return serializationObject;
  72256. };
  72257. /**
  72258. * Static members
  72259. */
  72260. // Parse serialized pipeline
  72261. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72262. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  72263. };
  72264. // Luminance steps
  72265. StandardRenderingPipeline.LuminanceSteps = 6;
  72266. __decorate([
  72267. BABYLON.serialize()
  72268. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  72269. __decorate([
  72270. BABYLON.serialize()
  72271. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  72272. __decorate([
  72273. BABYLON.serialize()
  72274. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  72275. __decorate([
  72276. BABYLON.serialize()
  72277. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  72278. __decorate([
  72279. BABYLON.serializeAsTexture("lensTexture")
  72280. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  72281. __decorate([
  72282. BABYLON.serialize()
  72283. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  72284. __decorate([
  72285. BABYLON.serialize()
  72286. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  72287. __decorate([
  72288. BABYLON.serialize()
  72289. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  72290. __decorate([
  72291. BABYLON.serialize()
  72292. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  72293. __decorate([
  72294. BABYLON.serialize()
  72295. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  72296. __decorate([
  72297. BABYLON.serialize()
  72298. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  72299. __decorate([
  72300. BABYLON.serializeAsTexture("lensColorTexture")
  72301. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  72302. __decorate([
  72303. BABYLON.serialize()
  72304. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  72305. __decorate([
  72306. BABYLON.serialize()
  72307. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  72308. __decorate([
  72309. BABYLON.serialize()
  72310. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  72311. __decorate([
  72312. BABYLON.serialize()
  72313. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  72314. __decorate([
  72315. BABYLON.serializeAsTexture("lensStarTexture")
  72316. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  72317. __decorate([
  72318. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  72319. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  72320. __decorate([
  72321. BABYLON.serialize()
  72322. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  72323. __decorate([
  72324. BABYLON.serialize()
  72325. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  72326. __decorate([
  72327. BABYLON.serialize()
  72328. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  72329. __decorate([
  72330. BABYLON.serialize()
  72331. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  72332. __decorate([
  72333. BABYLON.serialize()
  72334. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  72335. __decorate([
  72336. BABYLON.serialize()
  72337. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  72338. __decorate([
  72339. BABYLON.serialize()
  72340. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  72341. __decorate([
  72342. BABYLON.serialize()
  72343. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  72344. __decorate([
  72345. BABYLON.serialize()
  72346. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  72347. __decorate([
  72348. BABYLON.serialize()
  72349. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  72350. __decorate([
  72351. BABYLON.serialize()
  72352. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  72353. __decorate([
  72354. BABYLON.serialize()
  72355. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  72356. return StandardRenderingPipeline;
  72357. }(BABYLON.PostProcessRenderPipeline));
  72358. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  72359. })(BABYLON || (BABYLON = {}));
  72360. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  72361. "use strict";
  72362. var BABYLON;
  72363. (function (BABYLON) {
  72364. var FxaaPostProcess = /** @class */ (function (_super) {
  72365. __extends(FxaaPostProcess, _super);
  72366. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72367. if (camera === void 0) { camera = null; }
  72368. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72369. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  72370. _this.onApplyObservable.add(function (effect) {
  72371. var texelSize = _this.texelSize;
  72372. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  72373. });
  72374. return _this;
  72375. }
  72376. return FxaaPostProcess;
  72377. }(BABYLON.PostProcess));
  72378. BABYLON.FxaaPostProcess = FxaaPostProcess;
  72379. })(BABYLON || (BABYLON = {}));
  72380. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  72381. "use strict";
  72382. var BABYLON;
  72383. (function (BABYLON) {
  72384. /**
  72385. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  72386. */
  72387. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  72388. __extends(ChromaticAberrationPostProcess, _super);
  72389. /**
  72390. * Creates a new instance ChromaticAberrationPostProcess
  72391. * @param name The name of the effect.
  72392. * @param screenWidth The width of the screen to apply the effect on.
  72393. * @param screenHeight The height of the screen to apply the effect on.
  72394. * @param options The required width/height ratio to downsize to before computing the render pass.
  72395. * @param camera The camera to apply the render pass to.
  72396. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72397. * @param engine The engine which the post process will be applied. (default: current engine)
  72398. * @param reusable If the post process can be reused on the same frame. (default: false)
  72399. * @param textureType Type of textures used when performing the post process. (default: 0)
  72400. * @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)
  72401. */
  72402. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72403. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72404. if (blockCompilation === void 0) { blockCompilation = false; }
  72405. 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;
  72406. /**
  72407. * The amount of seperation of rgb channels (default: 30)
  72408. */
  72409. _this.aberrationAmount = 30;
  72410. /**
  72411. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  72412. */
  72413. _this.radialIntensity = 0;
  72414. /**
  72415. * 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))
  72416. */
  72417. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  72418. /**
  72419. * 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))
  72420. */
  72421. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  72422. _this.onApplyObservable.add(function (effect) {
  72423. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  72424. effect.setFloat('screen_width', screenWidth);
  72425. effect.setFloat('screen_height', screenHeight);
  72426. effect.setFloat('radialIntensity', _this.radialIntensity);
  72427. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  72428. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  72429. });
  72430. return _this;
  72431. }
  72432. return ChromaticAberrationPostProcess;
  72433. }(BABYLON.PostProcess));
  72434. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  72435. })(BABYLON || (BABYLON = {}));
  72436. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  72437. "use strict";
  72438. var BABYLON;
  72439. (function (BABYLON) {
  72440. /**
  72441. * The GrainPostProcess adds noise to the image at mid luminance levels
  72442. */
  72443. var GrainPostProcess = /** @class */ (function (_super) {
  72444. __extends(GrainPostProcess, _super);
  72445. /**
  72446. * Creates a new instance of @see GrainPostProcess
  72447. * @param name The name of the effect.
  72448. * @param options The required width/height ratio to downsize to before computing the render pass.
  72449. * @param camera The camera to apply the render pass to.
  72450. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72451. * @param engine The engine which the post process will be applied. (default: current engine)
  72452. * @param reusable If the post process can be reused on the same frame. (default: false)
  72453. * @param textureType Type of textures used when performing the post process. (default: 0)
  72454. * @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)
  72455. */
  72456. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72457. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72458. if (blockCompilation === void 0) { blockCompilation = false; }
  72459. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72460. /**
  72461. * The intensity of the grain added (default: 30)
  72462. */
  72463. _this.intensity = 30;
  72464. /**
  72465. * If the grain should be randomized on every frame
  72466. */
  72467. _this.animated = false;
  72468. _this.onApplyObservable.add(function (effect) {
  72469. effect.setFloat('intensity', _this.intensity);
  72470. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  72471. });
  72472. return _this;
  72473. }
  72474. return GrainPostProcess;
  72475. }(BABYLON.PostProcess));
  72476. BABYLON.GrainPostProcess = GrainPostProcess;
  72477. })(BABYLON || (BABYLON = {}));
  72478. //# sourceMappingURL=babylon.grainPostProcess.js.map
  72479. "use strict";
  72480. var BABYLON;
  72481. (function (BABYLON) {
  72482. /**
  72483. * The SharpenPostProcess applies a sharpen kernel to every pixel
  72484. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72485. */
  72486. var SharpenPostProcess = /** @class */ (function (_super) {
  72487. __extends(SharpenPostProcess, _super);
  72488. /**
  72489. * Creates a new instance ConvolutionPostProcess
  72490. * @param name The name of the effect.
  72491. * @param options The required width/height ratio to downsize to before computing the render pass.
  72492. * @param camera The camera to apply the render pass to.
  72493. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72494. * @param engine The engine which the post process will be applied. (default: current engine)
  72495. * @param reusable If the post process can be reused on the same frame. (default: false)
  72496. * @param textureType Type of textures used when performing the post process. (default: 0)
  72497. * @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)
  72498. */
  72499. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72500. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72501. if (blockCompilation === void 0) { blockCompilation = false; }
  72502. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72503. /**
  72504. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  72505. */
  72506. _this.colorAmount = 1.0;
  72507. /**
  72508. * How much sharpness should be applied (default: 0.3)
  72509. */
  72510. _this.edgeAmount = 0.3;
  72511. _this.onApply = function (effect) {
  72512. effect.setFloat2("screenSize", _this.width, _this.height);
  72513. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  72514. };
  72515. return _this;
  72516. }
  72517. return SharpenPostProcess;
  72518. }(BABYLON.PostProcess));
  72519. BABYLON.SharpenPostProcess = SharpenPostProcess;
  72520. })(BABYLON || (BABYLON = {}));
  72521. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  72522. "use strict";
  72523. var BABYLON;
  72524. (function (BABYLON) {
  72525. /**
  72526. * The Blur Post Process which blurs an image based on a kernel and direction.
  72527. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  72528. */
  72529. var BlurPostProcess = /** @class */ (function (_super) {
  72530. __extends(BlurPostProcess, _super);
  72531. /**
  72532. * Creates a new instance BlurPostProcess
  72533. * @param name The name of the effect.
  72534. * @param direction The direction in which to blur the image.
  72535. * @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.
  72536. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72537. * @param camera The camera to apply the render pass to.
  72538. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72539. * @param engine The engine which the post process will be applied. (default: current engine)
  72540. * @param reusable If the post process can be reused on the same frame. (default: false)
  72541. * @param textureType Type of textures used when performing the post process. (default: 0)
  72542. * @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)
  72543. */
  72544. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  72545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72546. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72547. if (defines === void 0) { defines = ""; }
  72548. if (blockCompilation === void 0) { blockCompilation = false; }
  72549. 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;
  72550. _this.direction = direction;
  72551. _this.blockCompilation = blockCompilation;
  72552. _this._packedFloat = false;
  72553. _this._staticDefines = "";
  72554. _this._staticDefines = defines;
  72555. _this.onApplyObservable.add(function (effect) {
  72556. if (_this._outputTexture) {
  72557. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  72558. }
  72559. else {
  72560. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  72561. }
  72562. });
  72563. _this.kernel = kernel;
  72564. return _this;
  72565. }
  72566. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  72567. /**
  72568. * Gets the length in pixels of the blur sample region
  72569. */
  72570. get: function () {
  72571. return this._idealKernel;
  72572. },
  72573. /**
  72574. * Sets the length in pixels of the blur sample region
  72575. */
  72576. set: function (v) {
  72577. if (this._idealKernel === v) {
  72578. return;
  72579. }
  72580. v = Math.max(v, 1);
  72581. this._idealKernel = v;
  72582. this._kernel = this._nearestBestKernel(v);
  72583. if (!this.blockCompilation) {
  72584. this._updateParameters();
  72585. }
  72586. },
  72587. enumerable: true,
  72588. configurable: true
  72589. });
  72590. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  72591. /**
  72592. * Gets wether or not the blur is unpacking/repacking floats
  72593. */
  72594. get: function () {
  72595. return this._packedFloat;
  72596. },
  72597. /**
  72598. * Sets wether or not the blur needs to unpack/repack floats
  72599. */
  72600. set: function (v) {
  72601. if (this._packedFloat === v) {
  72602. return;
  72603. }
  72604. this._packedFloat = v;
  72605. if (!this.blockCompilation) {
  72606. this._updateParameters();
  72607. }
  72608. },
  72609. enumerable: true,
  72610. configurable: true
  72611. });
  72612. /**
  72613. * Updates the effect with the current post process compile time values and recompiles the shader.
  72614. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72615. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72616. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72617. * @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
  72618. * @param onCompiled Called when the shader has been compiled.
  72619. * @param onError Called if there is an error when compiling a shader.
  72620. */
  72621. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72622. if (defines === void 0) { defines = null; }
  72623. if (uniforms === void 0) { uniforms = null; }
  72624. if (samplers === void 0) { samplers = null; }
  72625. this._updateParameters(onCompiled, onError);
  72626. };
  72627. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  72628. // Generate sampling offsets and weights
  72629. var N = this._kernel;
  72630. var centerIndex = (N - 1) / 2;
  72631. // Generate Gaussian sampling weights over kernel
  72632. var offsets = [];
  72633. var weights = [];
  72634. var totalWeight = 0;
  72635. for (var i = 0; i < N; i++) {
  72636. var u = i / (N - 1);
  72637. var w = this._gaussianWeight(u * 2.0 - 1);
  72638. offsets[i] = (i - centerIndex);
  72639. weights[i] = w;
  72640. totalWeight += w;
  72641. }
  72642. // Normalize weights
  72643. for (var i = 0; i < weights.length; i++) {
  72644. weights[i] /= totalWeight;
  72645. }
  72646. // Optimize: combine samples to take advantage of hardware linear sampling
  72647. // Walk from left to center, combining pairs (symmetrically)
  72648. var linearSamplingWeights = [];
  72649. var linearSamplingOffsets = [];
  72650. var linearSamplingMap = [];
  72651. for (var i = 0; i <= centerIndex; i += 2) {
  72652. var j = Math.min(i + 1, Math.floor(centerIndex));
  72653. var singleCenterSample = i === j;
  72654. if (singleCenterSample) {
  72655. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  72656. }
  72657. else {
  72658. var sharedCell = j === centerIndex;
  72659. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  72660. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  72661. if (offsetLinear === 0) {
  72662. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  72663. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  72664. }
  72665. else {
  72666. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  72667. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  72668. }
  72669. }
  72670. }
  72671. for (var i = 0; i < linearSamplingMap.length; i++) {
  72672. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  72673. linearSamplingWeights[i] = linearSamplingMap[i].w;
  72674. }
  72675. // Replace with optimized
  72676. offsets = linearSamplingOffsets;
  72677. weights = linearSamplingWeights;
  72678. // Generate shaders
  72679. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  72680. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  72681. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  72682. var defines = "";
  72683. defines += this._staticDefines;
  72684. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  72685. if (this._staticDefines.indexOf("DOF") != -1) {
  72686. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  72687. varyingCount--;
  72688. }
  72689. for (var i = 0; i < varyingCount; i++) {
  72690. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  72691. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  72692. }
  72693. var depCount = 0;
  72694. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  72695. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  72696. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  72697. depCount++;
  72698. }
  72699. if (this.packedFloat) {
  72700. defines += "#define PACKEDFLOAT 1";
  72701. }
  72702. this.blockCompilation = false;
  72703. _super.prototype.updateEffect.call(this, defines, null, null, {
  72704. varyingCount: varyingCount,
  72705. depCount: depCount
  72706. }, onCompiled, onError);
  72707. };
  72708. /**
  72709. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  72710. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  72711. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  72712. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  72713. * The gaps between physical kernels are compensated for in the weighting of the samples
  72714. * @param idealKernel Ideal blur kernel.
  72715. * @return Nearest best kernel.
  72716. */
  72717. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  72718. var v = Math.round(idealKernel);
  72719. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  72720. var k = _a[_i];
  72721. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  72722. return Math.max(k, 3);
  72723. }
  72724. }
  72725. return Math.max(v, 3);
  72726. };
  72727. /**
  72728. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  72729. * @param x The point on the Gaussian distribution to sample.
  72730. * @return the value of the Gaussian function at x.
  72731. */
  72732. BlurPostProcess.prototype._gaussianWeight = function (x) {
  72733. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  72734. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  72735. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  72736. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  72737. // truncated at around 1.3% of peak strength.
  72738. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  72739. var sigma = (1 / 3);
  72740. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  72741. var exponent = -((x * x) / (2.0 * sigma * sigma));
  72742. var weight = (1.0 / denominator) * Math.exp(exponent);
  72743. return weight;
  72744. };
  72745. /**
  72746. * Generates a string that can be used as a floating point number in GLSL.
  72747. * @param x Value to print.
  72748. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  72749. * @return GLSL float string.
  72750. */
  72751. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  72752. if (decimalFigures === void 0) { decimalFigures = 8; }
  72753. return x.toFixed(decimalFigures).replace(/0+$/, '');
  72754. };
  72755. return BlurPostProcess;
  72756. }(BABYLON.PostProcess));
  72757. BABYLON.BlurPostProcess = BlurPostProcess;
  72758. })(BABYLON || (BABYLON = {}));
  72759. //# sourceMappingURL=babylon.blurPostProcess.js.map
  72760. "use strict";
  72761. var BABYLON;
  72762. (function (BABYLON) {
  72763. /**
  72764. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  72765. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  72766. * based on samples that have a large difference in distance than the center pixel.
  72767. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  72768. */
  72769. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  72770. __extends(DepthOfFieldBlurPostProcess, _super);
  72771. /**
  72772. * Creates a new instance CircleOfConfusionPostProcess
  72773. * @param name The name of the effect.
  72774. * @param scene The scene the effect belongs to.
  72775. * @param direction The direction the blur should be applied.
  72776. * @param kernel The size of the kernel used to blur.
  72777. * @param options The required width/height ratio to downsize to before computing the render pass.
  72778. * @param camera The camera to apply the render pass to.
  72779. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  72780. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  72781. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72782. * @param engine The engine which the post process will be applied. (default: current engine)
  72783. * @param reusable If the post process can be reused on the same frame. (default: false)
  72784. * @param textureType Type of textures used when performing the post process. (default: 0)
  72785. * @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)
  72786. */
  72787. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  72788. if (imageToBlur === void 0) { imageToBlur = null; }
  72789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72790. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72791. if (blockCompilation === void 0) { blockCompilation = false; }
  72792. 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;
  72793. _this.direction = direction;
  72794. _this.onApplyObservable.add(function (effect) {
  72795. if (imageToBlur != null) {
  72796. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  72797. }
  72798. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  72799. if (scene.activeCamera) {
  72800. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  72801. }
  72802. });
  72803. return _this;
  72804. }
  72805. return DepthOfFieldBlurPostProcess;
  72806. }(BABYLON.BlurPostProcess));
  72807. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  72808. })(BABYLON || (BABYLON = {}));
  72809. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  72810. "use strict";
  72811. var BABYLON;
  72812. (function (BABYLON) {
  72813. /**
  72814. * Options to be set when merging outputs from the default pipeline.
  72815. */
  72816. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  72817. function DepthOfFieldMergePostProcessOptions() {
  72818. }
  72819. return DepthOfFieldMergePostProcessOptions;
  72820. }());
  72821. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  72822. /**
  72823. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  72824. */
  72825. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  72826. __extends(DepthOfFieldMergePostProcess, _super);
  72827. /**
  72828. * Creates a new instance of DepthOfFieldMergePostProcess
  72829. * @param name The name of the effect.
  72830. * @param originalFromInput Post process which's input will be used for the merge.
  72831. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  72832. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  72833. * @param options The required width/height ratio to downsize to before computing the render pass.
  72834. * @param camera The camera to apply the render pass to.
  72835. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72836. * @param engine The engine which the post process will be applied. (default: current engine)
  72837. * @param reusable If the post process can be reused on the same frame. (default: false)
  72838. * @param textureType Type of textures used when performing the post process. (default: 0)
  72839. * @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)
  72840. */
  72841. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72842. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72843. if (blockCompilation === void 0) { blockCompilation = false; }
  72844. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  72845. _this.blurSteps = blurSteps;
  72846. _this.onApplyObservable.add(function (effect) {
  72847. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  72848. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  72849. blurSteps.forEach(function (step, index) {
  72850. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  72851. });
  72852. });
  72853. if (!blockCompilation) {
  72854. _this.updateEffect();
  72855. }
  72856. return _this;
  72857. }
  72858. /**
  72859. * Updates the effect with the current post process compile time values and recompiles the shader.
  72860. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72861. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72862. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72863. * @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
  72864. * @param onCompiled Called when the shader has been compiled.
  72865. * @param onError Called if there is an error when compiling a shader.
  72866. */
  72867. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72868. if (defines === void 0) { defines = null; }
  72869. if (uniforms === void 0) { uniforms = null; }
  72870. if (samplers === void 0) { samplers = null; }
  72871. if (!defines) {
  72872. defines = "";
  72873. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  72874. }
  72875. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  72876. };
  72877. return DepthOfFieldMergePostProcess;
  72878. }(BABYLON.PostProcess));
  72879. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  72880. })(BABYLON || (BABYLON = {}));
  72881. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  72882. "use strict";
  72883. var BABYLON;
  72884. (function (BABYLON) {
  72885. /**
  72886. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  72887. */
  72888. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  72889. __extends(CircleOfConfusionPostProcess, _super);
  72890. /**
  72891. * Creates a new instance CircleOfConfusionPostProcess
  72892. * @param name The name of the effect.
  72893. * @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.
  72894. * @param options The required width/height ratio to downsize to before computing the render pass.
  72895. * @param camera The camera to apply the render pass to.
  72896. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72897. * @param engine The engine which the post process will be applied. (default: current engine)
  72898. * @param reusable If the post process can be reused on the same frame. (default: false)
  72899. * @param textureType Type of textures used when performing the post process. (default: 0)
  72900. * @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)
  72901. */
  72902. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72904. if (blockCompilation === void 0) { blockCompilation = false; }
  72905. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72906. /**
  72907. * 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.
  72908. */
  72909. _this.lensSize = 50;
  72910. /**
  72911. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  72912. */
  72913. _this.fStop = 1.4;
  72914. /**
  72915. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  72916. */
  72917. _this.focusDistance = 2000;
  72918. /**
  72919. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  72920. */
  72921. _this.focalLength = 50;
  72922. _this._depthTexture = null;
  72923. _this._depthTexture = depthTexture;
  72924. _this.onApplyObservable.add(function (effect) {
  72925. if (!_this._depthTexture) {
  72926. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  72927. return;
  72928. }
  72929. effect.setTexture("depthSampler", _this._depthTexture);
  72930. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  72931. var aperture = _this.lensSize / _this.fStop;
  72932. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  72933. effect.setFloat('focusDistance', _this.focusDistance);
  72934. effect.setFloat('cocPrecalculation', cocPrecalculation);
  72935. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  72936. });
  72937. return _this;
  72938. }
  72939. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  72940. /**
  72941. * 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.
  72942. */
  72943. set: function (value) {
  72944. this._depthTexture = value;
  72945. },
  72946. enumerable: true,
  72947. configurable: true
  72948. });
  72949. return CircleOfConfusionPostProcess;
  72950. }(BABYLON.PostProcess));
  72951. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  72952. })(BABYLON || (BABYLON = {}));
  72953. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  72954. "use strict";
  72955. var BABYLON;
  72956. (function (BABYLON) {
  72957. /**
  72958. * Specifies the level of max blur that should be applied when using the depth of field effect
  72959. */
  72960. var DepthOfFieldEffectBlurLevel;
  72961. (function (DepthOfFieldEffectBlurLevel) {
  72962. /**
  72963. * Subtle blur
  72964. */
  72965. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  72966. /**
  72967. * Medium blur
  72968. */
  72969. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  72970. /**
  72971. * Large blur
  72972. */
  72973. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  72974. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  72975. ;
  72976. /**
  72977. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  72978. */
  72979. var DepthOfFieldEffect = /** @class */ (function (_super) {
  72980. __extends(DepthOfFieldEffect, _super);
  72981. /**
  72982. * Creates a new instance DepthOfFieldEffect
  72983. * @param scene The scene the effect belongs to.
  72984. * @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.
  72985. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  72986. * @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)
  72987. */
  72988. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  72989. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  72990. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  72991. if (blockCompilation === void 0) { blockCompilation = false; }
  72992. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  72993. return _this._effects;
  72994. }, true) || this;
  72995. /**
  72996. * Internal post processes in depth of field effect
  72997. */
  72998. _this._effects = [];
  72999. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73000. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73001. // 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)
  73002. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73003. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73004. _this._depthOfFieldBlurY = [];
  73005. _this._depthOfFieldBlurX = [];
  73006. var blurCount = 1;
  73007. var kernelSize = 15;
  73008. switch (blurLevel) {
  73009. case DepthOfFieldEffectBlurLevel.High: {
  73010. blurCount = 3;
  73011. kernelSize = 51;
  73012. break;
  73013. }
  73014. case DepthOfFieldEffectBlurLevel.Medium: {
  73015. blurCount = 2;
  73016. kernelSize = 31;
  73017. break;
  73018. }
  73019. default: {
  73020. kernelSize = 15;
  73021. blurCount = 1;
  73022. break;
  73023. }
  73024. }
  73025. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73026. var ratio = 1.0;
  73027. for (var i = 0; i < blurCount; i++) {
  73028. 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);
  73029. blurY.autoClear = false;
  73030. ratio = 0.75 / Math.pow(2, i);
  73031. 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);
  73032. blurX.autoClear = false;
  73033. _this._depthOfFieldBlurY.push(blurY);
  73034. _this._depthOfFieldBlurX.push(blurX);
  73035. }
  73036. // Set all post processes on the effect.
  73037. _this._effects = [_this._circleOfConfusion];
  73038. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  73039. _this._effects.push(_this._depthOfFieldBlurY[i]);
  73040. _this._effects.push(_this._depthOfFieldBlurX[i]);
  73041. }
  73042. // Merge blurred images with original image based on circleOfConfusion
  73043. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73044. _this._dofMerge.autoClear = false;
  73045. _this._effects.push(_this._dofMerge);
  73046. return _this;
  73047. }
  73048. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  73049. get: function () {
  73050. return this._circleOfConfusion.focalLength;
  73051. },
  73052. /**
  73053. * The focal the length of the camera used in the effect
  73054. */
  73055. set: function (value) {
  73056. this._circleOfConfusion.focalLength = value;
  73057. },
  73058. enumerable: true,
  73059. configurable: true
  73060. });
  73061. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  73062. get: function () {
  73063. return this._circleOfConfusion.fStop;
  73064. },
  73065. /**
  73066. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73067. */
  73068. set: function (value) {
  73069. this._circleOfConfusion.fStop = value;
  73070. },
  73071. enumerable: true,
  73072. configurable: true
  73073. });
  73074. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  73075. get: function () {
  73076. return this._circleOfConfusion.focusDistance;
  73077. },
  73078. /**
  73079. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73080. */
  73081. set: function (value) {
  73082. this._circleOfConfusion.focusDistance = value;
  73083. },
  73084. enumerable: true,
  73085. configurable: true
  73086. });
  73087. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73088. get: function () {
  73089. return this._circleOfConfusion.lensSize;
  73090. },
  73091. /**
  73092. * 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.
  73093. */
  73094. set: function (value) {
  73095. this._circleOfConfusion.lensSize = value;
  73096. },
  73097. enumerable: true,
  73098. configurable: true
  73099. });
  73100. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73101. /**
  73102. * 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.
  73103. */
  73104. set: function (value) {
  73105. this._circleOfConfusion.depthTexture = value;
  73106. },
  73107. enumerable: true,
  73108. configurable: true
  73109. });
  73110. /**
  73111. * Disposes each of the internal effects for a given camera.
  73112. * @param camera The camera to dispose the effect on.
  73113. */
  73114. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73115. for (var effect in this._effects) {
  73116. this._effects[effect].dispose(camera);
  73117. }
  73118. };
  73119. /**
  73120. * Internal
  73121. */
  73122. DepthOfFieldEffect.prototype._updateEffects = function () {
  73123. for (var effect in this._effects) {
  73124. this._effects[effect].updateEffect();
  73125. }
  73126. };
  73127. /**
  73128. * Internal
  73129. * @returns if all the contained post processes are ready.
  73130. */
  73131. DepthOfFieldEffect.prototype._isReady = function () {
  73132. for (var effect in this._effects) {
  73133. if (!this._effects[effect].isReady()) {
  73134. return false;
  73135. }
  73136. }
  73137. return true;
  73138. };
  73139. return DepthOfFieldEffect;
  73140. }(BABYLON.PostProcessRenderEffect));
  73141. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73142. })(BABYLON || (BABYLON = {}));
  73143. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73144. "use strict";
  73145. var BABYLON;
  73146. (function (BABYLON) {
  73147. /**
  73148. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73149. */
  73150. var BloomMergePostProcess = /** @class */ (function (_super) {
  73151. __extends(BloomMergePostProcess, _super);
  73152. /**
  73153. * Creates a new instance of @see BloomMergePostProcess
  73154. * @param name The name of the effect.
  73155. * @param originalFromInput Post process which's input will be used for the merge.
  73156. * @param blurred Blurred highlights post process which's output will be used.
  73157. * @param weight Weight of the bloom to be added to the original input.
  73158. * @param options The required width/height ratio to downsize to before computing the render pass.
  73159. * @param camera The camera to apply the render pass to.
  73160. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73161. * @param engine The engine which the post process will be applied. (default: current engine)
  73162. * @param reusable If the post process can be reused on the same frame. (default: false)
  73163. * @param textureType Type of textures used when performing the post process. (default: 0)
  73164. * @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)
  73165. */
  73166. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73167. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73168. if (blockCompilation === void 0) { blockCompilation = false; }
  73169. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73170. _this.weight = weight;
  73171. _this.onApplyObservable.add(function (effect) {
  73172. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73173. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73174. effect.setFloat("bloomWeight", _this.weight);
  73175. });
  73176. if (!blockCompilation) {
  73177. _this.updateEffect();
  73178. }
  73179. return _this;
  73180. }
  73181. return BloomMergePostProcess;
  73182. }(BABYLON.PostProcess));
  73183. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73184. })(BABYLON || (BABYLON = {}));
  73185. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73186. "use strict";
  73187. var BABYLON;
  73188. (function (BABYLON) {
  73189. /**
  73190. * 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.
  73191. */
  73192. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73193. __extends(ExtractHighlightsPostProcess, _super);
  73194. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73195. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73196. if (blockCompilation === void 0) { blockCompilation = false; }
  73197. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73198. /**
  73199. * The luminance threshold, pixels below this value will be set to black.
  73200. */
  73201. _this.threshold = 0.9;
  73202. /**
  73203. * Internal
  73204. */
  73205. _this._exposure = 1;
  73206. /**
  73207. * Post process which has the input texture to be used when performing highlight extraction
  73208. */
  73209. _this._inputPostProcess = null;
  73210. _this.onApplyObservable.add(function (effect) {
  73211. if (_this._inputPostProcess) {
  73212. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  73213. }
  73214. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  73215. effect.setFloat('exposure', _this._exposure);
  73216. });
  73217. return _this;
  73218. }
  73219. return ExtractHighlightsPostProcess;
  73220. }(BABYLON.PostProcess));
  73221. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  73222. })(BABYLON || (BABYLON = {}));
  73223. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  73224. "use strict";
  73225. var BABYLON;
  73226. (function (BABYLON) {
  73227. /**
  73228. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  73229. */
  73230. var BloomEffect = /** @class */ (function (_super) {
  73231. __extends(BloomEffect, _super);
  73232. /**
  73233. * Creates a new instance of @see BloomEffect
  73234. * @param scene The scene the effect belongs to.
  73235. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  73236. * @param bloomKernel The size of the kernel to be used when applying the blur.
  73237. * @param bloomWeight The the strength of bloom.
  73238. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73239. * @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)
  73240. */
  73241. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  73242. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73243. if (blockCompilation === void 0) { blockCompilation = false; }
  73244. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  73245. return _this._effects;
  73246. }, true) || this;
  73247. _this.bloomScale = bloomScale;
  73248. /**
  73249. * Internal
  73250. */
  73251. _this._effects = [];
  73252. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73253. _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);
  73254. _this._blurX.alwaysForcePOT = true;
  73255. _this._blurX.autoClear = false;
  73256. _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);
  73257. _this._blurY.alwaysForcePOT = true;
  73258. _this._blurY.autoClear = false;
  73259. _this.kernel = bloomKernel;
  73260. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  73261. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73262. _this._merge.autoClear = false;
  73263. _this._effects.push(_this._merge);
  73264. return _this;
  73265. }
  73266. Object.defineProperty(BloomEffect.prototype, "threshold", {
  73267. /**
  73268. * The luminance threshold to find bright areas of the image to bloom.
  73269. */
  73270. get: function () {
  73271. return this._downscale.threshold;
  73272. },
  73273. set: function (value) {
  73274. this._downscale.threshold = value;
  73275. },
  73276. enumerable: true,
  73277. configurable: true
  73278. });
  73279. Object.defineProperty(BloomEffect.prototype, "weight", {
  73280. /**
  73281. * The strength of the bloom.
  73282. */
  73283. get: function () {
  73284. return this._merge.weight;
  73285. },
  73286. set: function (value) {
  73287. this._merge.weight = value;
  73288. },
  73289. enumerable: true,
  73290. configurable: true
  73291. });
  73292. Object.defineProperty(BloomEffect.prototype, "kernel", {
  73293. /**
  73294. * Specifies the size of the bloom blur kernel, relative to the final output size
  73295. */
  73296. get: function () {
  73297. return this._blurX.kernel / this.bloomScale;
  73298. },
  73299. set: function (value) {
  73300. this._blurX.kernel = value * this.bloomScale;
  73301. this._blurY.kernel = value * this.bloomScale;
  73302. },
  73303. enumerable: true,
  73304. configurable: true
  73305. });
  73306. /**
  73307. * Disposes each of the internal effects for a given camera.
  73308. * @param camera The camera to dispose the effect on.
  73309. */
  73310. BloomEffect.prototype.disposeEffects = function (camera) {
  73311. for (var effect in this._effects) {
  73312. this._effects[effect].dispose(camera);
  73313. }
  73314. };
  73315. /**
  73316. * Internal
  73317. */
  73318. BloomEffect.prototype._updateEffects = function () {
  73319. for (var effect in this._effects) {
  73320. this._effects[effect].updateEffect();
  73321. }
  73322. };
  73323. /**
  73324. * Internal
  73325. * @returns if all the contained post processes are ready.
  73326. */
  73327. BloomEffect.prototype._isReady = function () {
  73328. for (var effect in this._effects) {
  73329. if (!this._effects[effect].isReady()) {
  73330. return false;
  73331. }
  73332. }
  73333. return true;
  73334. };
  73335. return BloomEffect;
  73336. }(BABYLON.PostProcessRenderEffect));
  73337. BABYLON.BloomEffect = BloomEffect;
  73338. })(BABYLON || (BABYLON = {}));
  73339. //# sourceMappingURL=babylon.bloomEffect.js.map
  73340. "use strict";
  73341. var BABYLON;
  73342. (function (BABYLON) {
  73343. /**
  73344. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  73345. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  73346. */
  73347. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  73348. __extends(DefaultRenderingPipeline, _super);
  73349. /**
  73350. * @constructor
  73351. * @param {string} name - The rendering pipeline name
  73352. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73353. * @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)
  73354. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73355. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  73356. */
  73357. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  73358. if (automaticBuild === void 0) { automaticBuild = true; }
  73359. var _this = _super.call(this, scene.getEngine(), name) || this;
  73360. _this._originalCameras = [];
  73361. /**
  73362. * ID of the sharpen post process,
  73363. */
  73364. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  73365. /**
  73366. * ID of the image processing post process;
  73367. */
  73368. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  73369. /**
  73370. * ID of the Fast Approximate Anti-Aliasing post process;
  73371. */
  73372. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  73373. /**
  73374. * ID of the chromatic aberration post process,
  73375. */
  73376. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  73377. /**
  73378. * ID of the grain post process
  73379. */
  73380. _this.GrainPostProcessId = "GrainPostProcessEffect";
  73381. /**
  73382. * Animations which can be used to tweak settings over a period of time
  73383. */
  73384. _this.animations = [];
  73385. _this._imageProcessingConfigurationObserver = null;
  73386. // Values
  73387. _this._sharpenEnabled = false;
  73388. _this._bloomEnabled = false;
  73389. _this._depthOfFieldEnabled = false;
  73390. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  73391. _this._fxaaEnabled = false;
  73392. _this._imageProcessingEnabled = true;
  73393. _this._bloomScale = 0.5;
  73394. _this._chromaticAberrationEnabled = false;
  73395. _this._grainEnabled = false;
  73396. _this._buildAllowed = true;
  73397. _this._resizeObserver = null;
  73398. _this._hardwareScaleLevel = 1.0;
  73399. _this._bloomKernel = 64;
  73400. /**
  73401. * Specifies the weight of the bloom in the final rendering
  73402. */
  73403. _this._bloomWeight = 0.15;
  73404. /**
  73405. * Specifies the luma threshold for the area that will be blurred by the bloom
  73406. */
  73407. _this._bloomThreshold = 0.9;
  73408. _this._samples = 1;
  73409. _this._hasCleared = false;
  73410. _this._prevPostProcess = null;
  73411. _this._prevPrevPostProcess = null;
  73412. _this._cameras = cameras || [];
  73413. _this._originalCameras = _this._cameras.slice();
  73414. _this._buildAllowed = automaticBuild;
  73415. // Initialize
  73416. _this._scene = scene;
  73417. var caps = _this._scene.getEngine().getCaps();
  73418. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  73419. // Misc
  73420. if (_this._hdr) {
  73421. if (caps.textureHalfFloatRender) {
  73422. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73423. }
  73424. else if (caps.textureFloatRender) {
  73425. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73426. }
  73427. }
  73428. else {
  73429. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73430. }
  73431. // Attach
  73432. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73433. var engine = _this._scene.getEngine();
  73434. // Create post processes before hand so they can be modified before enabled.
  73435. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  73436. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73437. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  73438. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  73439. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  73440. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73441. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  73442. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73443. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  73444. _this._resizeObserver = engine.onResizeObservable.add(function () {
  73445. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  73446. _this.bloomKernel = _this.bloomKernel;
  73447. });
  73448. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73449. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  73450. });
  73451. _this._buildPipeline();
  73452. return _this;
  73453. }
  73454. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  73455. get: function () {
  73456. return this._sharpenEnabled;
  73457. },
  73458. /**
  73459. * Enable or disable the sharpen process from the pipeline
  73460. */
  73461. set: function (enabled) {
  73462. if (this._sharpenEnabled === enabled) {
  73463. return;
  73464. }
  73465. this._sharpenEnabled = enabled;
  73466. this._buildPipeline();
  73467. },
  73468. enumerable: true,
  73469. configurable: true
  73470. });
  73471. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  73472. /**
  73473. * Specifies the size of the bloom blur kernel, relative to the final output size
  73474. */
  73475. get: function () {
  73476. return this._bloomKernel;
  73477. },
  73478. set: function (value) {
  73479. this._bloomKernel = value;
  73480. this.bloom.kernel = value / this._hardwareScaleLevel;
  73481. },
  73482. enumerable: true,
  73483. configurable: true
  73484. });
  73485. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  73486. get: function () {
  73487. return this._bloomWeight;
  73488. },
  73489. /**
  73490. * The strength of the bloom.
  73491. */
  73492. set: function (value) {
  73493. if (this._bloomWeight === value) {
  73494. return;
  73495. }
  73496. this.bloom.weight = value;
  73497. this._bloomWeight = value;
  73498. },
  73499. enumerable: true,
  73500. configurable: true
  73501. });
  73502. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  73503. get: function () {
  73504. return this._bloomThreshold;
  73505. },
  73506. /**
  73507. * The strength of the bloom.
  73508. */
  73509. set: function (value) {
  73510. if (this._bloomThreshold === value) {
  73511. return;
  73512. }
  73513. this.bloom.threshold = value;
  73514. this._bloomThreshold = value;
  73515. },
  73516. enumerable: true,
  73517. configurable: true
  73518. });
  73519. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  73520. get: function () {
  73521. return this._bloomScale;
  73522. },
  73523. /**
  73524. * The scale of the bloom, lower value will provide better performance.
  73525. */
  73526. set: function (value) {
  73527. if (this._bloomScale === value) {
  73528. return;
  73529. }
  73530. this._bloomScale = value;
  73531. // recreate bloom and dispose old as this setting is not dynamic
  73532. this._rebuildBloom();
  73533. this._buildPipeline();
  73534. },
  73535. enumerable: true,
  73536. configurable: true
  73537. });
  73538. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  73539. get: function () {
  73540. return this._bloomEnabled;
  73541. },
  73542. /**
  73543. * Enable or disable the bloom from the pipeline
  73544. */
  73545. set: function (enabled) {
  73546. if (this._bloomEnabled === enabled) {
  73547. return;
  73548. }
  73549. this._bloomEnabled = enabled;
  73550. this._buildPipeline();
  73551. },
  73552. enumerable: true,
  73553. configurable: true
  73554. });
  73555. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  73556. // recreate bloom and dispose old as this setting is not dynamic
  73557. var oldBloom = this.bloom;
  73558. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  73559. this.bloom.threshold = oldBloom.threshold;
  73560. for (var i = 0; i < this._cameras.length; i++) {
  73561. oldBloom.disposeEffects(this._cameras[i]);
  73562. }
  73563. };
  73564. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  73565. /**
  73566. * If the depth of field is enabled.
  73567. */
  73568. get: function () {
  73569. return this._depthOfFieldEnabled;
  73570. },
  73571. set: function (enabled) {
  73572. if (this._depthOfFieldEnabled === enabled) {
  73573. return;
  73574. }
  73575. this._depthOfFieldEnabled = enabled;
  73576. this._buildPipeline();
  73577. },
  73578. enumerable: true,
  73579. configurable: true
  73580. });
  73581. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  73582. /**
  73583. * Blur level of the depth of field effect. (Higher blur will effect performance)
  73584. */
  73585. get: function () {
  73586. return this._depthOfFieldBlurLevel;
  73587. },
  73588. set: function (value) {
  73589. if (this._depthOfFieldBlurLevel === value) {
  73590. return;
  73591. }
  73592. this._depthOfFieldBlurLevel = value;
  73593. // recreate dof and dispose old as this setting is not dynamic
  73594. var oldDof = this.depthOfField;
  73595. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  73596. this.depthOfField.focalLength = oldDof.focalLength;
  73597. this.depthOfField.focusDistance = oldDof.focusDistance;
  73598. this.depthOfField.fStop = oldDof.fStop;
  73599. this.depthOfField.lensSize = oldDof.lensSize;
  73600. for (var i = 0; i < this._cameras.length; i++) {
  73601. oldDof.disposeEffects(this._cameras[i]);
  73602. }
  73603. this._buildPipeline();
  73604. },
  73605. enumerable: true,
  73606. configurable: true
  73607. });
  73608. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  73609. get: function () {
  73610. return this._fxaaEnabled;
  73611. },
  73612. /**
  73613. * If the anti aliasing is enabled.
  73614. */
  73615. set: function (enabled) {
  73616. if (this._fxaaEnabled === enabled) {
  73617. return;
  73618. }
  73619. this._fxaaEnabled = enabled;
  73620. this._buildPipeline();
  73621. },
  73622. enumerable: true,
  73623. configurable: true
  73624. });
  73625. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  73626. get: function () {
  73627. return this._samples;
  73628. },
  73629. /**
  73630. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  73631. */
  73632. set: function (sampleCount) {
  73633. if (this._samples === sampleCount) {
  73634. return;
  73635. }
  73636. this._samples = sampleCount;
  73637. this._buildPipeline();
  73638. },
  73639. enumerable: true,
  73640. configurable: true
  73641. });
  73642. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  73643. get: function () {
  73644. return this._imageProcessingEnabled;
  73645. },
  73646. /**
  73647. * If image processing is enabled.
  73648. */
  73649. set: function (enabled) {
  73650. if (this._imageProcessingEnabled === enabled) {
  73651. return;
  73652. }
  73653. this._imageProcessingEnabled = enabled;
  73654. this._buildPipeline();
  73655. },
  73656. enumerable: true,
  73657. configurable: true
  73658. });
  73659. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  73660. get: function () {
  73661. return this._chromaticAberrationEnabled;
  73662. },
  73663. /**
  73664. * Enable or disable the chromaticAberration process from the pipeline
  73665. */
  73666. set: function (enabled) {
  73667. if (this._chromaticAberrationEnabled === enabled) {
  73668. return;
  73669. }
  73670. this._chromaticAberrationEnabled = enabled;
  73671. this._buildPipeline();
  73672. },
  73673. enumerable: true,
  73674. configurable: true
  73675. });
  73676. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  73677. get: function () {
  73678. return this._grainEnabled;
  73679. },
  73680. /**
  73681. * Enable or disable the grain process from the pipeline
  73682. */
  73683. set: function (enabled) {
  73684. if (this._grainEnabled === enabled) {
  73685. return;
  73686. }
  73687. this._grainEnabled = enabled;
  73688. this._buildPipeline();
  73689. },
  73690. enumerable: true,
  73691. configurable: true
  73692. });
  73693. /**
  73694. * Force the compilation of the entire pipeline.
  73695. */
  73696. DefaultRenderingPipeline.prototype.prepare = function () {
  73697. var previousState = this._buildAllowed;
  73698. this._buildAllowed = true;
  73699. this._buildPipeline();
  73700. this._buildAllowed = previousState;
  73701. };
  73702. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  73703. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  73704. if (this._hasCleared) {
  73705. postProcess.autoClear = false;
  73706. }
  73707. else {
  73708. postProcess.autoClear = true;
  73709. this._scene.autoClear = false;
  73710. this._hasCleared = true;
  73711. }
  73712. if (!skipTextureSharing) {
  73713. if (this._prevPrevPostProcess) {
  73714. postProcess.shareOutputWith(this._prevPrevPostProcess);
  73715. }
  73716. else {
  73717. postProcess.useOwnOutput();
  73718. }
  73719. if (this._prevPostProcess) {
  73720. this._prevPrevPostProcess = this._prevPostProcess;
  73721. }
  73722. this._prevPostProcess = postProcess;
  73723. }
  73724. };
  73725. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  73726. var _this = this;
  73727. if (!this._buildAllowed) {
  73728. return;
  73729. }
  73730. this._scene.autoClear = true;
  73731. var engine = this._scene.getEngine();
  73732. this._disposePostProcesses();
  73733. if (this._cameras !== null) {
  73734. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73735. // get back cameras to be used to reattach pipeline
  73736. this._cameras = this._originalCameras.slice();
  73737. }
  73738. this._reset();
  73739. this._prevPostProcess = null;
  73740. this._prevPrevPostProcess = null;
  73741. this._hasCleared = false;
  73742. if (this.depthOfFieldEnabled) {
  73743. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  73744. this.depthOfField.depthTexture = depthTexture;
  73745. if (!this.depthOfField._isReady()) {
  73746. this.depthOfField._updateEffects();
  73747. }
  73748. this.addEffect(this.depthOfField);
  73749. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  73750. }
  73751. if (this.bloomEnabled) {
  73752. if (!this.bloom._isReady()) {
  73753. this.bloom._updateEffects();
  73754. }
  73755. this.addEffect(this.bloom);
  73756. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  73757. }
  73758. if (this._imageProcessingEnabled) {
  73759. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  73760. if (this._hdr) {
  73761. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  73762. this._setAutoClearAndTextureSharing(this.imageProcessing);
  73763. }
  73764. else {
  73765. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  73766. }
  73767. }
  73768. if (this.sharpenEnabled) {
  73769. if (!this.sharpen.isReady()) {
  73770. this.sharpen.updateEffect();
  73771. }
  73772. this.addEffect(this._sharpenEffect);
  73773. this._setAutoClearAndTextureSharing(this.sharpen);
  73774. }
  73775. if (this.grainEnabled) {
  73776. if (!this.grain.isReady()) {
  73777. this.grain.updateEffect();
  73778. }
  73779. this.addEffect(this._grainEffect);
  73780. this._setAutoClearAndTextureSharing(this.grain);
  73781. }
  73782. if (this.chromaticAberrationEnabled) {
  73783. if (!this.chromaticAberration.isReady()) {
  73784. this.chromaticAberration.updateEffect();
  73785. }
  73786. this.addEffect(this._chromaticAberrationEffect);
  73787. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  73788. }
  73789. if (this.fxaaEnabled) {
  73790. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  73791. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  73792. this._setAutoClearAndTextureSharing(this.fxaa, true);
  73793. }
  73794. if (this._cameras !== null) {
  73795. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73796. }
  73797. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  73798. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  73799. }
  73800. };
  73801. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  73802. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  73803. for (var i = 0; i < this._cameras.length; i++) {
  73804. var camera = this._cameras[i];
  73805. if (this.imageProcessing) {
  73806. this.imageProcessing.dispose(camera);
  73807. }
  73808. if (this.fxaa) {
  73809. this.fxaa.dispose(camera);
  73810. }
  73811. // These are created in the constructor and should not be disposed on every pipeline change
  73812. if (disposeNonRecreated) {
  73813. if (this.sharpen) {
  73814. this.sharpen.dispose(camera);
  73815. }
  73816. if (this.depthOfField) {
  73817. this.depthOfField.disposeEffects(camera);
  73818. }
  73819. if (this.bloom) {
  73820. this.bloom.disposeEffects(camera);
  73821. }
  73822. if (this.chromaticAberration) {
  73823. this.chromaticAberration.dispose(camera);
  73824. }
  73825. if (this.grain) {
  73826. this.grain.dispose(camera);
  73827. }
  73828. }
  73829. }
  73830. this.imageProcessing = null;
  73831. this.fxaa = null;
  73832. if (disposeNonRecreated) {
  73833. this.sharpen = null;
  73834. this._sharpenEffect = null;
  73835. this.depthOfField = null;
  73836. this.bloom = null;
  73837. this.chromaticAberration = null;
  73838. this._chromaticAberrationEffect = null;
  73839. this.grain = null;
  73840. this._grainEffect = null;
  73841. }
  73842. };
  73843. /**
  73844. * Dispose of the pipeline and stop all post processes
  73845. */
  73846. DefaultRenderingPipeline.prototype.dispose = function () {
  73847. this._disposePostProcesses(true);
  73848. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73849. this._scene.autoClear = true;
  73850. if (this._resizeObserver) {
  73851. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  73852. this._resizeObserver = null;
  73853. }
  73854. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  73855. _super.prototype.dispose.call(this);
  73856. };
  73857. /**
  73858. * Serialize the rendering pipeline (Used when exporting)
  73859. * @returns the serialized object
  73860. */
  73861. DefaultRenderingPipeline.prototype.serialize = function () {
  73862. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73863. serializationObject.customType = "DefaultRenderingPipeline";
  73864. return serializationObject;
  73865. };
  73866. /**
  73867. * Parse the serialized pipeline
  73868. * @param source Source pipeline.
  73869. * @param scene The scene to load the pipeline to.
  73870. * @param rootUrl The URL of the serialized pipeline.
  73871. * @returns An instantiated pipeline from the serialized object.
  73872. */
  73873. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73874. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  73875. };
  73876. __decorate([
  73877. BABYLON.serialize()
  73878. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  73879. __decorate([
  73880. BABYLON.serialize()
  73881. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  73882. __decorate([
  73883. BABYLON.serialize()
  73884. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  73885. __decorate([
  73886. BABYLON.serialize()
  73887. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  73888. __decorate([
  73889. BABYLON.serialize()
  73890. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  73891. __decorate([
  73892. BABYLON.serialize()
  73893. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  73894. __decorate([
  73895. BABYLON.serialize()
  73896. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  73897. __decorate([
  73898. BABYLON.serialize()
  73899. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  73900. __decorate([
  73901. BABYLON.serialize()
  73902. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  73903. __decorate([
  73904. BABYLON.serialize()
  73905. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  73906. __decorate([
  73907. BABYLON.serialize()
  73908. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  73909. __decorate([
  73910. BABYLON.serialize()
  73911. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  73912. __decorate([
  73913. BABYLON.serialize()
  73914. ], DefaultRenderingPipeline.prototype, "samples", null);
  73915. __decorate([
  73916. BABYLON.serialize()
  73917. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  73918. __decorate([
  73919. BABYLON.serialize()
  73920. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  73921. __decorate([
  73922. BABYLON.serialize()
  73923. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  73924. return DefaultRenderingPipeline;
  73925. }(BABYLON.PostProcessRenderPipeline));
  73926. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  73927. })(BABYLON || (BABYLON = {}));
  73928. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  73929. "use strict";
  73930. var BABYLON;
  73931. (function (BABYLON) {
  73932. /**
  73933. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  73934. */
  73935. var GeometryBufferRenderer = /** @class */ (function () {
  73936. /**
  73937. * Creates a new G Buffer for the scene
  73938. * @param scene The scene the buffer belongs to
  73939. * @param ratio How big is the buffer related to the main canvas.
  73940. */
  73941. function GeometryBufferRenderer(scene, ratio) {
  73942. if (ratio === void 0) { ratio = 1; }
  73943. this._enablePosition = false;
  73944. this._scene = scene;
  73945. this._ratio = ratio;
  73946. // Render target
  73947. this._createRenderTargets();
  73948. }
  73949. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  73950. /**
  73951. * Set the render list (meshes to be rendered) used in the G buffer.
  73952. */
  73953. set: function (meshes) {
  73954. this._multiRenderTarget.renderList = meshes;
  73955. },
  73956. enumerable: true,
  73957. configurable: true
  73958. });
  73959. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  73960. /**
  73961. * Gets wether or not G buffer are supported by the running hardware.
  73962. * This requires draw buffer supports
  73963. */
  73964. get: function () {
  73965. return this._multiRenderTarget.isSupported;
  73966. },
  73967. enumerable: true,
  73968. configurable: true
  73969. });
  73970. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  73971. /**
  73972. * Gets wether or not position are enabled for the G buffer.
  73973. */
  73974. get: function () {
  73975. return this._enablePosition;
  73976. },
  73977. /**
  73978. * Sets wether or not position are enabled for the G buffer.
  73979. */
  73980. set: function (enable) {
  73981. this._enablePosition = enable;
  73982. this.dispose();
  73983. this._createRenderTargets();
  73984. },
  73985. enumerable: true,
  73986. configurable: true
  73987. });
  73988. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  73989. /**
  73990. * Gets the scene associated with the buffer.
  73991. */
  73992. get: function () {
  73993. return this._scene;
  73994. },
  73995. enumerable: true,
  73996. configurable: true
  73997. });
  73998. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  73999. /**
  74000. * Gets the ratio used by the buffer during its creation.
  74001. * How big is the buffer related to the main canvas.
  74002. */
  74003. get: function () {
  74004. return this._ratio;
  74005. },
  74006. enumerable: true,
  74007. configurable: true
  74008. });
  74009. /**
  74010. * Checks wether everything is ready to render a submesh to the G buffer.
  74011. * @param subMesh the submesh to check readiness for
  74012. * @param useInstances is the mesh drawn using instance or not
  74013. * @returns true if ready otherwise false
  74014. */
  74015. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74016. var material = subMesh.getMaterial();
  74017. if (material && material.disableDepthWrite) {
  74018. return false;
  74019. }
  74020. var defines = [];
  74021. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74022. var mesh = subMesh.getMesh();
  74023. // Alpha test
  74024. if (material && material.needAlphaTesting()) {
  74025. defines.push("#define ALPHATEST");
  74026. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74027. attribs.push(BABYLON.VertexBuffer.UVKind);
  74028. defines.push("#define UV1");
  74029. }
  74030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74031. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74032. defines.push("#define UV2");
  74033. }
  74034. }
  74035. // Buffers
  74036. if (this._enablePosition) {
  74037. defines.push("#define POSITION");
  74038. }
  74039. // Bones
  74040. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74043. if (mesh.numBoneInfluencers > 4) {
  74044. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74045. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74046. }
  74047. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74048. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74049. }
  74050. else {
  74051. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74052. }
  74053. // Instances
  74054. if (useInstances) {
  74055. defines.push("#define INSTANCES");
  74056. attribs.push("world0");
  74057. attribs.push("world1");
  74058. attribs.push("world2");
  74059. attribs.push("world3");
  74060. }
  74061. // Get correct effect
  74062. var join = defines.join("\n");
  74063. if (this._cachedDefines !== join) {
  74064. this._cachedDefines = join;
  74065. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  74066. }
  74067. return this._effect.isReady();
  74068. };
  74069. /**
  74070. * Gets the current underlying G Buffer.
  74071. * @returns the buffer
  74072. */
  74073. GeometryBufferRenderer.prototype.getGBuffer = function () {
  74074. return this._multiRenderTarget;
  74075. };
  74076. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  74077. /**
  74078. * Gets the number of samples used to render the buffer (anti aliasing).
  74079. */
  74080. get: function () {
  74081. return this._multiRenderTarget.samples;
  74082. },
  74083. /**
  74084. * Sets the number of samples used to render the buffer (anti aliasing).
  74085. */
  74086. set: function (value) {
  74087. this._multiRenderTarget.samples = value;
  74088. },
  74089. enumerable: true,
  74090. configurable: true
  74091. });
  74092. /**
  74093. * Disposes the renderer and frees up associated resources.
  74094. */
  74095. GeometryBufferRenderer.prototype.dispose = function () {
  74096. this.getGBuffer().dispose();
  74097. };
  74098. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74099. var _this = this;
  74100. var engine = this._scene.getEngine();
  74101. var count = this._enablePosition ? 3 : 2;
  74102. 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 });
  74103. if (!this.isSupported) {
  74104. return;
  74105. }
  74106. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74107. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74108. this._multiRenderTarget.refreshRate = 1;
  74109. this._multiRenderTarget.renderParticles = false;
  74110. this._multiRenderTarget.renderList = null;
  74111. // set default depth value to 1.0 (far away)
  74112. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74113. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74114. });
  74115. // Custom render function
  74116. var renderSubMesh = function (subMesh) {
  74117. var mesh = subMesh.getRenderingMesh();
  74118. var scene = _this._scene;
  74119. var engine = scene.getEngine();
  74120. var material = subMesh.getMaterial();
  74121. if (!material) {
  74122. return;
  74123. }
  74124. // Culling
  74125. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74126. // Managing instances
  74127. var batch = mesh._getInstancesRenderList(subMesh._id);
  74128. if (batch.mustReturn) {
  74129. return;
  74130. }
  74131. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74132. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74133. engine.enableEffect(_this._effect);
  74134. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74135. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74136. _this._effect.setMatrix("view", scene.getViewMatrix());
  74137. // Alpha test
  74138. if (material && material.needAlphaTesting()) {
  74139. var alphaTexture = material.getAlphaTestTexture();
  74140. if (alphaTexture) {
  74141. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74142. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74143. }
  74144. }
  74145. // Bones
  74146. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74147. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74148. }
  74149. // Draw
  74150. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74151. }
  74152. };
  74153. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74154. var index;
  74155. if (depthOnlySubMeshes.length) {
  74156. engine.setColorWrite(false);
  74157. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74158. renderSubMesh(depthOnlySubMeshes.data[index]);
  74159. }
  74160. engine.setColorWrite(true);
  74161. }
  74162. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74163. renderSubMesh(opaqueSubMeshes.data[index]);
  74164. }
  74165. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74166. renderSubMesh(alphaTestSubMeshes.data[index]);
  74167. }
  74168. };
  74169. };
  74170. return GeometryBufferRenderer;
  74171. }());
  74172. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74173. })(BABYLON || (BABYLON = {}));
  74174. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74175. "use strict";
  74176. var BABYLON;
  74177. (function (BABYLON) {
  74178. var RefractionPostProcess = /** @class */ (function (_super) {
  74179. __extends(RefractionPostProcess, _super);
  74180. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74181. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74182. _this.color = color;
  74183. _this.depth = depth;
  74184. _this.colorLevel = colorLevel;
  74185. _this._ownRefractionTexture = true;
  74186. _this.onActivateObservable.add(function (cam) {
  74187. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74188. });
  74189. _this.onApplyObservable.add(function (effect) {
  74190. effect.setColor3("baseColor", _this.color);
  74191. effect.setFloat("depth", _this.depth);
  74192. effect.setFloat("colorLevel", _this.colorLevel);
  74193. effect.setTexture("refractionSampler", _this._refTexture);
  74194. });
  74195. return _this;
  74196. }
  74197. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74198. /**
  74199. * Gets or sets the refraction texture
  74200. * Please note that you are responsible for disposing the texture if you set it manually
  74201. */
  74202. get: function () {
  74203. return this._refTexture;
  74204. },
  74205. set: function (value) {
  74206. if (this._refTexture && this._ownRefractionTexture) {
  74207. this._refTexture.dispose();
  74208. }
  74209. this._refTexture = value;
  74210. this._ownRefractionTexture = false;
  74211. },
  74212. enumerable: true,
  74213. configurable: true
  74214. });
  74215. // Methods
  74216. RefractionPostProcess.prototype.dispose = function (camera) {
  74217. if (this._refTexture && this._ownRefractionTexture) {
  74218. this._refTexture.dispose();
  74219. this._refTexture = null;
  74220. }
  74221. _super.prototype.dispose.call(this, camera);
  74222. };
  74223. return RefractionPostProcess;
  74224. }(BABYLON.PostProcess));
  74225. BABYLON.RefractionPostProcess = RefractionPostProcess;
  74226. })(BABYLON || (BABYLON = {}));
  74227. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  74228. "use strict";
  74229. var BABYLON;
  74230. (function (BABYLON) {
  74231. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  74232. __extends(BlackAndWhitePostProcess, _super);
  74233. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  74234. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  74235. _this.degree = 1;
  74236. _this.onApplyObservable.add(function (effect) {
  74237. effect.setFloat("degree", _this.degree);
  74238. });
  74239. return _this;
  74240. }
  74241. return BlackAndWhitePostProcess;
  74242. }(BABYLON.PostProcess));
  74243. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  74244. })(BABYLON || (BABYLON = {}));
  74245. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  74246. "use strict";
  74247. var BABYLON;
  74248. (function (BABYLON) {
  74249. /**
  74250. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  74251. * input texture to perform effects such as edge detection or sharpening
  74252. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74253. */
  74254. var ConvolutionPostProcess = /** @class */ (function (_super) {
  74255. __extends(ConvolutionPostProcess, _super);
  74256. /**
  74257. * Creates a new instance ConvolutionPostProcess
  74258. * @param name The name of the effect.
  74259. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  74260. * @param options The required width/height ratio to downsize to before computing the render pass.
  74261. * @param camera The camera to apply the render pass to.
  74262. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74263. * @param engine The engine which the post process will be applied. (default: current engine)
  74264. * @param reusable If the post process can be reused on the same frame. (default: false)
  74265. * @param textureType Type of textures used when performing the post process. (default: 0)
  74266. */
  74267. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  74268. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74269. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74270. _this.kernel = kernel;
  74271. _this.onApply = function (effect) {
  74272. effect.setFloat2("screenSize", _this.width, _this.height);
  74273. effect.setArray("kernel", _this.kernel);
  74274. };
  74275. return _this;
  74276. }
  74277. // Statics
  74278. /**
  74279. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74280. */
  74281. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  74282. /**
  74283. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74284. */
  74285. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  74286. /**
  74287. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74288. */
  74289. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  74290. /**
  74291. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74292. */
  74293. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  74294. /**
  74295. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74296. */
  74297. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  74298. /**
  74299. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74300. */
  74301. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  74302. return ConvolutionPostProcess;
  74303. }(BABYLON.PostProcess));
  74304. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  74305. })(BABYLON || (BABYLON = {}));
  74306. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  74307. "use strict";
  74308. var BABYLON;
  74309. (function (BABYLON) {
  74310. var FilterPostProcess = /** @class */ (function (_super) {
  74311. __extends(FilterPostProcess, _super);
  74312. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  74313. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  74314. _this.kernelMatrix = kernelMatrix;
  74315. _this.onApply = function (effect) {
  74316. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  74317. };
  74318. return _this;
  74319. }
  74320. return FilterPostProcess;
  74321. }(BABYLON.PostProcess));
  74322. BABYLON.FilterPostProcess = FilterPostProcess;
  74323. })(BABYLON || (BABYLON = {}));
  74324. //# sourceMappingURL=babylon.filterPostProcess.js.map
  74325. "use strict";
  74326. var BABYLON;
  74327. (function (BABYLON) {
  74328. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  74329. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  74330. __extends(VolumetricLightScatteringPostProcess, _super);
  74331. /**
  74332. * @constructor
  74333. * @param {string} name - The post-process name
  74334. * @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)
  74335. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  74336. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  74337. * @param {number} samples - The post-process quality, default 100
  74338. * @param {number} samplingMode - The post-process filtering mode
  74339. * @param {BABYLON.Engine} engine - The babylon engine
  74340. * @param {boolean} reusable - If the post-process is reusable
  74341. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  74342. */
  74343. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  74344. if (samples === void 0) { samples = 100; }
  74345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74346. 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;
  74347. _this._screenCoordinates = BABYLON.Vector2.Zero();
  74348. /**
  74349. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  74350. */
  74351. _this.customMeshPosition = BABYLON.Vector3.Zero();
  74352. /**
  74353. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  74354. */
  74355. _this.useCustomMeshPosition = false;
  74356. /**
  74357. * If the post-process should inverse the light scattering direction
  74358. */
  74359. _this.invert = true;
  74360. /**
  74361. * Array containing the excluded meshes not rendered in the internal pass
  74362. */
  74363. _this.excludedMeshes = new Array();
  74364. /**
  74365. * Controls the overall intensity of the post-process
  74366. */
  74367. _this.exposure = 0.3;
  74368. /**
  74369. * Dissipates each sample's contribution in range [0, 1]
  74370. */
  74371. _this.decay = 0.96815;
  74372. /**
  74373. * Controls the overall intensity of each sample
  74374. */
  74375. _this.weight = 0.58767;
  74376. /**
  74377. * Controls the density of each sample
  74378. */
  74379. _this.density = 0.926;
  74380. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  74381. engine = scene.getEngine();
  74382. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  74383. // Configure mesh
  74384. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  74385. // Configure
  74386. _this._createPass(scene, ratio.passRatio || ratio);
  74387. _this.onActivate = function (camera) {
  74388. if (!_this.isSupported) {
  74389. _this.dispose(camera);
  74390. }
  74391. _this.onActivate = null;
  74392. };
  74393. _this.onApplyObservable.add(function (effect) {
  74394. _this._updateMeshScreenCoordinates(scene);
  74395. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  74396. effect.setFloat("exposure", _this.exposure);
  74397. effect.setFloat("decay", _this.decay);
  74398. effect.setFloat("weight", _this.weight);
  74399. effect.setFloat("density", _this.density);
  74400. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  74401. });
  74402. return _this;
  74403. }
  74404. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  74405. get: function () {
  74406. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74407. return false;
  74408. },
  74409. set: function (useDiffuseColor) {
  74410. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74411. },
  74412. enumerable: true,
  74413. configurable: true
  74414. });
  74415. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  74416. return "VolumetricLightScatteringPostProcess";
  74417. };
  74418. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  74419. var mesh = subMesh.getMesh();
  74420. // Render this.mesh as default
  74421. if (mesh === this.mesh && mesh.material) {
  74422. return mesh.material.isReady(mesh);
  74423. }
  74424. var defines = [];
  74425. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74426. var material = subMesh.getMaterial();
  74427. // Alpha test
  74428. if (material) {
  74429. if (material.needAlphaTesting()) {
  74430. defines.push("#define ALPHATEST");
  74431. }
  74432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74433. attribs.push(BABYLON.VertexBuffer.UVKind);
  74434. defines.push("#define UV1");
  74435. }
  74436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74437. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74438. defines.push("#define UV2");
  74439. }
  74440. }
  74441. // Bones
  74442. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74443. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74444. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74445. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74446. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74447. }
  74448. else {
  74449. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74450. }
  74451. // Instances
  74452. if (useInstances) {
  74453. defines.push("#define INSTANCES");
  74454. attribs.push("world0");
  74455. attribs.push("world1");
  74456. attribs.push("world2");
  74457. attribs.push("world3");
  74458. }
  74459. // Get correct effect
  74460. var join = defines.join("\n");
  74461. if (this._cachedDefines !== join) {
  74462. this._cachedDefines = join;
  74463. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  74464. }
  74465. return this._volumetricLightScatteringPass.isReady();
  74466. };
  74467. /**
  74468. * Sets the new light position for light scattering effect
  74469. * @param {BABYLON.Vector3} The new custom light position
  74470. */
  74471. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  74472. this.customMeshPosition = position;
  74473. };
  74474. /**
  74475. * Returns the light position for light scattering effect
  74476. * @return {BABYLON.Vector3} The custom light position
  74477. */
  74478. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  74479. return this.customMeshPosition;
  74480. };
  74481. /**
  74482. * Disposes the internal assets and detaches the post-process from the camera
  74483. */
  74484. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  74485. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  74486. if (rttIndex !== -1) {
  74487. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  74488. }
  74489. this._volumetricLightScatteringRTT.dispose();
  74490. _super.prototype.dispose.call(this, camera);
  74491. };
  74492. /**
  74493. * Returns the render target texture used by the post-process
  74494. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  74495. */
  74496. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  74497. return this._volumetricLightScatteringRTT;
  74498. };
  74499. // Private methods
  74500. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  74501. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  74502. return true;
  74503. }
  74504. return false;
  74505. };
  74506. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  74507. var _this = this;
  74508. var engine = scene.getEngine();
  74509. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74510. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74511. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74512. this._volumetricLightScatteringRTT.renderList = null;
  74513. this._volumetricLightScatteringRTT.renderParticles = false;
  74514. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  74515. var camera = this.getCamera();
  74516. if (camera) {
  74517. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74518. }
  74519. else {
  74520. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74521. }
  74522. // Custom render function for submeshes
  74523. var renderSubMesh = function (subMesh) {
  74524. var mesh = subMesh.getRenderingMesh();
  74525. if (_this._meshExcluded(mesh)) {
  74526. return;
  74527. }
  74528. var material = subMesh.getMaterial();
  74529. if (!material) {
  74530. return;
  74531. }
  74532. var scene = mesh.getScene();
  74533. var engine = scene.getEngine();
  74534. // Culling
  74535. engine.setState(material.backFaceCulling);
  74536. // Managing instances
  74537. var batch = mesh._getInstancesRenderList(subMesh._id);
  74538. if (batch.mustReturn) {
  74539. return;
  74540. }
  74541. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74542. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  74543. var effect = _this._volumetricLightScatteringPass;
  74544. if (mesh === _this.mesh) {
  74545. if (subMesh.effect) {
  74546. effect = subMesh.effect;
  74547. }
  74548. else {
  74549. effect = material.getEffect();
  74550. }
  74551. }
  74552. engine.enableEffect(effect);
  74553. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  74554. if (mesh === _this.mesh) {
  74555. material.bind(mesh.getWorldMatrix(), mesh);
  74556. }
  74557. else {
  74558. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  74559. // Alpha test
  74560. if (material && material.needAlphaTesting()) {
  74561. var alphaTexture = material.getAlphaTestTexture();
  74562. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  74563. if (alphaTexture) {
  74564. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74565. }
  74566. }
  74567. // Bones
  74568. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74569. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74570. }
  74571. }
  74572. // Draw
  74573. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  74574. }
  74575. };
  74576. // Render target texture callbacks
  74577. var savedSceneClearColor;
  74578. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  74579. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  74580. savedSceneClearColor = scene.clearColor;
  74581. scene.clearColor = sceneClearColor;
  74582. });
  74583. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  74584. scene.clearColor = savedSceneClearColor;
  74585. });
  74586. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74587. var engine = scene.getEngine();
  74588. var index;
  74589. if (depthOnlySubMeshes.length) {
  74590. engine.setColorWrite(false);
  74591. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74592. renderSubMesh(depthOnlySubMeshes.data[index]);
  74593. }
  74594. engine.setColorWrite(true);
  74595. }
  74596. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74597. renderSubMesh(opaqueSubMeshes.data[index]);
  74598. }
  74599. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74600. renderSubMesh(alphaTestSubMeshes.data[index]);
  74601. }
  74602. if (transparentSubMeshes.length) {
  74603. // Sort sub meshes
  74604. for (index = 0; index < transparentSubMeshes.length; index++) {
  74605. var submesh = transparentSubMeshes.data[index];
  74606. var boundingInfo = submesh.getBoundingInfo();
  74607. if (boundingInfo && scene.activeCamera) {
  74608. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  74609. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  74610. }
  74611. }
  74612. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  74613. sortedArray.sort(function (a, b) {
  74614. // Alpha index first
  74615. if (a._alphaIndex > b._alphaIndex) {
  74616. return 1;
  74617. }
  74618. if (a._alphaIndex < b._alphaIndex) {
  74619. return -1;
  74620. }
  74621. // Then distance to camera
  74622. if (a._distanceToCamera < b._distanceToCamera) {
  74623. return 1;
  74624. }
  74625. if (a._distanceToCamera > b._distanceToCamera) {
  74626. return -1;
  74627. }
  74628. return 0;
  74629. });
  74630. // Render sub meshes
  74631. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  74632. for (index = 0; index < sortedArray.length; index++) {
  74633. renderSubMesh(sortedArray[index]);
  74634. }
  74635. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74636. }
  74637. };
  74638. };
  74639. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  74640. var transform = scene.getTransformMatrix();
  74641. var meshPosition;
  74642. if (this.useCustomMeshPosition) {
  74643. meshPosition = this.customMeshPosition;
  74644. }
  74645. else if (this.attachedNode) {
  74646. meshPosition = this.attachedNode.position;
  74647. }
  74648. else {
  74649. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  74650. }
  74651. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  74652. this._screenCoordinates.x = pos.x / this._viewPort.width;
  74653. this._screenCoordinates.y = pos.y / this._viewPort.height;
  74654. if (this.invert)
  74655. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  74656. };
  74657. // Static methods
  74658. /**
  74659. * Creates a default mesh for the Volumeric Light Scattering post-process
  74660. * @param {string} The mesh name
  74661. * @param {BABYLON.Scene} The scene where to create the mesh
  74662. * @return {BABYLON.Mesh} the default mesh
  74663. */
  74664. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  74665. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  74666. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  74667. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  74668. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  74669. mesh.material = material;
  74670. return mesh;
  74671. };
  74672. __decorate([
  74673. BABYLON.serializeAsVector3()
  74674. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  74675. __decorate([
  74676. BABYLON.serialize()
  74677. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  74678. __decorate([
  74679. BABYLON.serialize()
  74680. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  74681. __decorate([
  74682. BABYLON.serializeAsMeshReference()
  74683. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  74684. __decorate([
  74685. BABYLON.serialize()
  74686. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  74687. __decorate([
  74688. BABYLON.serialize()
  74689. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  74690. __decorate([
  74691. BABYLON.serialize()
  74692. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  74693. __decorate([
  74694. BABYLON.serialize()
  74695. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  74696. __decorate([
  74697. BABYLON.serialize()
  74698. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  74699. return VolumetricLightScatteringPostProcess;
  74700. }(BABYLON.PostProcess));
  74701. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  74702. })(BABYLON || (BABYLON = {}));
  74703. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  74704. "use strict";
  74705. //
  74706. // This post-process allows the modification of rendered colors by using
  74707. // a 'look-up table' (LUT). This effect is also called Color Grading.
  74708. //
  74709. // The object needs to be provided an url to a texture containing the color
  74710. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  74711. // Use an image editing software to tweak the LUT to match your needs.
  74712. //
  74713. // For an example of a color LUT, see here:
  74714. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  74715. // For explanations on color grading, see here:
  74716. // http://udn.epicgames.com/Three/ColorGrading.html
  74717. //
  74718. var BABYLON;
  74719. (function (BABYLON) {
  74720. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  74721. __extends(ColorCorrectionPostProcess, _super);
  74722. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  74723. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  74724. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74725. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  74726. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74727. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74728. _this.onApply = function (effect) {
  74729. effect.setTexture("colorTable", _this._colorTableTexture);
  74730. };
  74731. return _this;
  74732. }
  74733. return ColorCorrectionPostProcess;
  74734. }(BABYLON.PostProcess));
  74735. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  74736. })(BABYLON || (BABYLON = {}));
  74737. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  74738. "use strict";
  74739. var BABYLON;
  74740. (function (BABYLON) {
  74741. var TonemappingOperator;
  74742. (function (TonemappingOperator) {
  74743. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  74744. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  74745. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  74746. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  74747. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  74748. ;
  74749. var TonemapPostProcess = /** @class */ (function (_super) {
  74750. __extends(TonemapPostProcess, _super);
  74751. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  74752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74753. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74754. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  74755. _this._operator = _operator;
  74756. _this.exposureAdjustment = exposureAdjustment;
  74757. var defines = "#define ";
  74758. if (_this._operator === TonemappingOperator.Hable)
  74759. defines += "HABLE_TONEMAPPING";
  74760. else if (_this._operator === TonemappingOperator.Reinhard)
  74761. defines += "REINHARD_TONEMAPPING";
  74762. else if (_this._operator === TonemappingOperator.HejiDawson)
  74763. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  74764. else if (_this._operator === TonemappingOperator.Photographic)
  74765. defines += "PHOTOGRAPHIC_TONEMAPPING";
  74766. //sadly a second call to create the effect.
  74767. _this.updateEffect(defines);
  74768. _this.onApply = function (effect) {
  74769. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  74770. };
  74771. return _this;
  74772. }
  74773. return TonemapPostProcess;
  74774. }(BABYLON.PostProcess));
  74775. BABYLON.TonemapPostProcess = TonemapPostProcess;
  74776. })(BABYLON || (BABYLON = {}));
  74777. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  74778. "use strict";
  74779. var BABYLON;
  74780. (function (BABYLON) {
  74781. var DisplayPassPostProcess = /** @class */ (function (_super) {
  74782. __extends(DisplayPassPostProcess, _super);
  74783. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  74784. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  74785. }
  74786. return DisplayPassPostProcess;
  74787. }(BABYLON.PostProcess));
  74788. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  74789. })(BABYLON || (BABYLON = {}));
  74790. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  74791. "use strict";
  74792. var BABYLON;
  74793. (function (BABYLON) {
  74794. var HighlightsPostProcess = /** @class */ (function (_super) {
  74795. __extends(HighlightsPostProcess, _super);
  74796. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74797. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74798. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74799. }
  74800. return HighlightsPostProcess;
  74801. }(BABYLON.PostProcess));
  74802. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  74803. })(BABYLON || (BABYLON = {}));
  74804. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  74805. "use strict";
  74806. var BABYLON;
  74807. (function (BABYLON) {
  74808. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  74809. __extends(ImageProcessingPostProcess, _super);
  74810. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  74811. if (camera === void 0) { camera = null; }
  74812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74813. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  74814. _this._fromLinearSpace = true;
  74815. /**
  74816. * Defines cache preventing GC.
  74817. */
  74818. _this._defines = {
  74819. IMAGEPROCESSING: false,
  74820. VIGNETTE: false,
  74821. VIGNETTEBLENDMODEMULTIPLY: false,
  74822. VIGNETTEBLENDMODEOPAQUE: false,
  74823. TONEMAPPING: false,
  74824. CONTRAST: false,
  74825. COLORCURVES: false,
  74826. COLORGRADING: false,
  74827. COLORGRADING3D: false,
  74828. FROMLINEARSPACE: false,
  74829. SAMPLER3DGREENDEPTH: false,
  74830. SAMPLER3DBGRMAP: false,
  74831. IMAGEPROCESSINGPOSTPROCESS: false,
  74832. EXPOSURE: false,
  74833. };
  74834. // Setup the configuration as forced by the constructor. This would then not force the
  74835. // scene materials output in linear space and let untouched the default forward pass.
  74836. if (imageProcessingConfiguration) {
  74837. imageProcessingConfiguration.applyByPostProcess = true;
  74838. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  74839. // This will cause the shader to be compiled
  74840. _this.fromLinearSpace = false;
  74841. }
  74842. else {
  74843. _this._attachImageProcessingConfiguration(null, true);
  74844. _this.imageProcessingConfiguration.applyByPostProcess = true;
  74845. }
  74846. _this.onApply = function (effect) {
  74847. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  74848. };
  74849. return _this;
  74850. }
  74851. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  74852. /**
  74853. * Gets the image processing configuration used either in this material.
  74854. */
  74855. get: function () {
  74856. return this._imageProcessingConfiguration;
  74857. },
  74858. /**
  74859. * Sets the Default image processing configuration used either in the this material.
  74860. *
  74861. * If sets to null, the scene one is in use.
  74862. */
  74863. set: function (value) {
  74864. this._attachImageProcessingConfiguration(value);
  74865. },
  74866. enumerable: true,
  74867. configurable: true
  74868. });
  74869. /**
  74870. * Attaches a new image processing configuration to the PBR Material.
  74871. * @param configuration
  74872. */
  74873. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  74874. var _this = this;
  74875. if (doNotBuild === void 0) { doNotBuild = false; }
  74876. if (configuration === this._imageProcessingConfiguration) {
  74877. return;
  74878. }
  74879. // Detaches observer.
  74880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74882. }
  74883. // Pick the scene configuration if needed.
  74884. if (!configuration) {
  74885. var scene = null;
  74886. var engine = this.getEngine();
  74887. var camera = this.getCamera();
  74888. if (camera) {
  74889. scene = camera.getScene();
  74890. }
  74891. else if (engine && engine.scenes) {
  74892. var scenes = engine.scenes;
  74893. scene = scenes[scenes.length - 1];
  74894. }
  74895. else {
  74896. scene = BABYLON.Engine.LastCreatedScene;
  74897. }
  74898. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  74899. }
  74900. else {
  74901. this._imageProcessingConfiguration = configuration;
  74902. }
  74903. // Attaches observer.
  74904. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74905. _this._updateParameters();
  74906. });
  74907. // Ensure the effect will be rebuilt.
  74908. if (!doNotBuild) {
  74909. this._updateParameters();
  74910. }
  74911. };
  74912. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  74913. /**
  74914. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  74915. */
  74916. get: function () {
  74917. return this.imageProcessingConfiguration.colorCurves;
  74918. },
  74919. /**
  74920. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  74921. */
  74922. set: function (value) {
  74923. this.imageProcessingConfiguration.colorCurves = value;
  74924. },
  74925. enumerable: true,
  74926. configurable: true
  74927. });
  74928. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  74929. /**
  74930. * Gets wether the color curves effect is enabled.
  74931. */
  74932. get: function () {
  74933. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74934. },
  74935. /**
  74936. * Sets wether the color curves effect is enabled.
  74937. */
  74938. set: function (value) {
  74939. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74940. },
  74941. enumerable: true,
  74942. configurable: true
  74943. });
  74944. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  74945. /**
  74946. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  74947. */
  74948. get: function () {
  74949. return this.imageProcessingConfiguration.colorGradingTexture;
  74950. },
  74951. /**
  74952. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  74953. */
  74954. set: function (value) {
  74955. this.imageProcessingConfiguration.colorGradingTexture = value;
  74956. },
  74957. enumerable: true,
  74958. configurable: true
  74959. });
  74960. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  74961. /**
  74962. * Gets wether the color grading effect is enabled.
  74963. */
  74964. get: function () {
  74965. return this.imageProcessingConfiguration.colorGradingEnabled;
  74966. },
  74967. /**
  74968. * Gets wether the color grading effect is enabled.
  74969. */
  74970. set: function (value) {
  74971. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74972. },
  74973. enumerable: true,
  74974. configurable: true
  74975. });
  74976. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  74977. /**
  74978. * Gets exposure used in the effect.
  74979. */
  74980. get: function () {
  74981. return this.imageProcessingConfiguration.exposure;
  74982. },
  74983. /**
  74984. * Sets exposure used in the effect.
  74985. */
  74986. set: function (value) {
  74987. this.imageProcessingConfiguration.exposure = value;
  74988. },
  74989. enumerable: true,
  74990. configurable: true
  74991. });
  74992. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  74993. /**
  74994. * Gets wether tonemapping is enabled or not.
  74995. */
  74996. get: function () {
  74997. return this._imageProcessingConfiguration.toneMappingEnabled;
  74998. },
  74999. /**
  75000. * Sets wether tonemapping is enabled or not
  75001. */
  75002. set: function (value) {
  75003. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75004. },
  75005. enumerable: true,
  75006. configurable: true
  75007. });
  75008. ;
  75009. ;
  75010. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75011. /**
  75012. * Gets contrast used in the effect.
  75013. */
  75014. get: function () {
  75015. return this.imageProcessingConfiguration.contrast;
  75016. },
  75017. /**
  75018. * Sets contrast used in the effect.
  75019. */
  75020. set: function (value) {
  75021. this.imageProcessingConfiguration.contrast = value;
  75022. },
  75023. enumerable: true,
  75024. configurable: true
  75025. });
  75026. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75027. /**
  75028. * Gets Vignette stretch size.
  75029. */
  75030. get: function () {
  75031. return this.imageProcessingConfiguration.vignetteStretch;
  75032. },
  75033. /**
  75034. * Sets Vignette stretch size.
  75035. */
  75036. set: function (value) {
  75037. this.imageProcessingConfiguration.vignetteStretch = value;
  75038. },
  75039. enumerable: true,
  75040. configurable: true
  75041. });
  75042. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  75043. /**
  75044. * Gets Vignette centre X Offset.
  75045. */
  75046. get: function () {
  75047. return this.imageProcessingConfiguration.vignetteCentreX;
  75048. },
  75049. /**
  75050. * Sets Vignette centre X Offset.
  75051. */
  75052. set: function (value) {
  75053. this.imageProcessingConfiguration.vignetteCentreX = value;
  75054. },
  75055. enumerable: true,
  75056. configurable: true
  75057. });
  75058. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  75059. /**
  75060. * Gets Vignette centre Y Offset.
  75061. */
  75062. get: function () {
  75063. return this.imageProcessingConfiguration.vignetteCentreY;
  75064. },
  75065. /**
  75066. * Sets Vignette centre Y Offset.
  75067. */
  75068. set: function (value) {
  75069. this.imageProcessingConfiguration.vignetteCentreY = value;
  75070. },
  75071. enumerable: true,
  75072. configurable: true
  75073. });
  75074. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  75075. /**
  75076. * Gets Vignette weight or intensity of the vignette effect.
  75077. */
  75078. get: function () {
  75079. return this.imageProcessingConfiguration.vignetteWeight;
  75080. },
  75081. /**
  75082. * Sets Vignette weight or intensity of the vignette effect.
  75083. */
  75084. set: function (value) {
  75085. this.imageProcessingConfiguration.vignetteWeight = value;
  75086. },
  75087. enumerable: true,
  75088. configurable: true
  75089. });
  75090. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75091. /**
  75092. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75093. * if vignetteEnabled is set to true.
  75094. */
  75095. get: function () {
  75096. return this.imageProcessingConfiguration.vignetteColor;
  75097. },
  75098. /**
  75099. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75100. * if vignetteEnabled is set to true.
  75101. */
  75102. set: function (value) {
  75103. this.imageProcessingConfiguration.vignetteColor = value;
  75104. },
  75105. enumerable: true,
  75106. configurable: true
  75107. });
  75108. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75109. /**
  75110. * Gets Camera field of view used by the Vignette effect.
  75111. */
  75112. get: function () {
  75113. return this.imageProcessingConfiguration.vignetteCameraFov;
  75114. },
  75115. /**
  75116. * Sets Camera field of view used by the Vignette effect.
  75117. */
  75118. set: function (value) {
  75119. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75120. },
  75121. enumerable: true,
  75122. configurable: true
  75123. });
  75124. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75125. /**
  75126. * Gets the vignette blend mode allowing different kind of effect.
  75127. */
  75128. get: function () {
  75129. return this.imageProcessingConfiguration.vignetteBlendMode;
  75130. },
  75131. /**
  75132. * Sets the vignette blend mode allowing different kind of effect.
  75133. */
  75134. set: function (value) {
  75135. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75136. },
  75137. enumerable: true,
  75138. configurable: true
  75139. });
  75140. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75141. /**
  75142. * Gets wether the vignette effect is enabled.
  75143. */
  75144. get: function () {
  75145. return this.imageProcessingConfiguration.vignetteEnabled;
  75146. },
  75147. /**
  75148. * Sets wether the vignette effect is enabled.
  75149. */
  75150. set: function (value) {
  75151. this.imageProcessingConfiguration.vignetteEnabled = value;
  75152. },
  75153. enumerable: true,
  75154. configurable: true
  75155. });
  75156. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75157. /**
  75158. * Gets wether the input of the processing is in Gamma or Linear Space.
  75159. */
  75160. get: function () {
  75161. return this._fromLinearSpace;
  75162. },
  75163. /**
  75164. * Sets wether the input of the processing is in Gamma or Linear Space.
  75165. */
  75166. set: function (value) {
  75167. if (this._fromLinearSpace === value) {
  75168. return;
  75169. }
  75170. this._fromLinearSpace = value;
  75171. this._updateParameters();
  75172. },
  75173. enumerable: true,
  75174. configurable: true
  75175. });
  75176. ImageProcessingPostProcess.prototype.getClassName = function () {
  75177. return "ImageProcessingPostProcess";
  75178. };
  75179. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75180. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75181. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75182. var defines = "";
  75183. for (var define in this._defines) {
  75184. if (this._defines[define]) {
  75185. defines += "#define " + define + ";\r\n";
  75186. }
  75187. }
  75188. var samplers = ["textureSampler"];
  75189. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75190. var uniforms = ["scale"];
  75191. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75192. this.updateEffect(defines, uniforms, samplers);
  75193. };
  75194. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75195. _super.prototype.dispose.call(this, camera);
  75196. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75197. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75198. }
  75199. this.imageProcessingConfiguration.applyByPostProcess = false;
  75200. };
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75204. return ImageProcessingPostProcess;
  75205. }(BABYLON.PostProcess));
  75206. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75207. })(BABYLON || (BABYLON = {}));
  75208. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75209. "use strict";
  75210. var BABYLON;
  75211. (function (BABYLON) {
  75212. var Bone = /** @class */ (function (_super) {
  75213. __extends(Bone, _super);
  75214. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  75215. if (parentBone === void 0) { parentBone = null; }
  75216. if (localMatrix === void 0) { localMatrix = null; }
  75217. if (restPose === void 0) { restPose = null; }
  75218. if (baseMatrix === void 0) { baseMatrix = null; }
  75219. if (index === void 0) { index = null; }
  75220. var _this = _super.call(this, name, skeleton.getScene()) || this;
  75221. _this.name = name;
  75222. _this.children = new Array();
  75223. _this.animations = new Array();
  75224. // Set this value to map this bone to a different index in the transform matrices.
  75225. // Set this value to -1 to exclude the bone from the transform matrices.
  75226. _this._index = null;
  75227. _this._worldTransform = new BABYLON.Matrix();
  75228. _this._absoluteTransform = new BABYLON.Matrix();
  75229. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  75230. _this._scaleMatrix = BABYLON.Matrix.Identity();
  75231. _this._scaleVector = BABYLON.Vector3.One();
  75232. _this._negateScaleChildren = BABYLON.Vector3.One();
  75233. _this._scalingDeterminant = 1;
  75234. _this._skeleton = skeleton;
  75235. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  75236. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  75237. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  75238. _this._index = index;
  75239. skeleton.bones.push(_this);
  75240. _this.setParent(parentBone, false);
  75241. _this._updateDifferenceMatrix();
  75242. return _this;
  75243. }
  75244. Object.defineProperty(Bone.prototype, "_matrix", {
  75245. get: function () {
  75246. return this._localMatrix;
  75247. },
  75248. set: function (val) {
  75249. if (this._localMatrix) {
  75250. this._localMatrix.copyFrom(val);
  75251. }
  75252. else {
  75253. this._localMatrix = val;
  75254. }
  75255. },
  75256. enumerable: true,
  75257. configurable: true
  75258. });
  75259. // Members
  75260. Bone.prototype.getSkeleton = function () {
  75261. return this._skeleton;
  75262. };
  75263. Bone.prototype.getParent = function () {
  75264. return this._parent;
  75265. };
  75266. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  75267. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75268. if (this._parent === parent) {
  75269. return;
  75270. }
  75271. if (this._parent) {
  75272. var index = this._parent.children.indexOf(this);
  75273. if (index !== -1) {
  75274. this._parent.children.splice(index, 1);
  75275. }
  75276. }
  75277. this._parent = parent;
  75278. if (this._parent) {
  75279. this._parent.children.push(this);
  75280. }
  75281. if (updateDifferenceMatrix) {
  75282. this._updateDifferenceMatrix();
  75283. }
  75284. };
  75285. Bone.prototype.getLocalMatrix = function () {
  75286. return this._localMatrix;
  75287. };
  75288. Bone.prototype.getBaseMatrix = function () {
  75289. return this._baseMatrix;
  75290. };
  75291. Bone.prototype.getRestPose = function () {
  75292. return this._restPose;
  75293. };
  75294. Bone.prototype.returnToRest = function () {
  75295. this.updateMatrix(this._restPose.clone());
  75296. };
  75297. Bone.prototype.getWorldMatrix = function () {
  75298. return this._worldTransform;
  75299. };
  75300. Bone.prototype.getInvertedAbsoluteTransform = function () {
  75301. return this._invertedAbsoluteTransform;
  75302. };
  75303. Bone.prototype.getAbsoluteTransform = function () {
  75304. return this._absoluteTransform;
  75305. };
  75306. Object.defineProperty(Bone.prototype, "position", {
  75307. // Properties (matches AbstractMesh properties)
  75308. get: function () {
  75309. return this.getPosition();
  75310. },
  75311. set: function (newPosition) {
  75312. this.setPosition(newPosition);
  75313. },
  75314. enumerable: true,
  75315. configurable: true
  75316. });
  75317. Object.defineProperty(Bone.prototype, "rotation", {
  75318. get: function () {
  75319. return this.getRotation();
  75320. },
  75321. set: function (newRotation) {
  75322. this.setRotation(newRotation);
  75323. },
  75324. enumerable: true,
  75325. configurable: true
  75326. });
  75327. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  75328. get: function () {
  75329. return this.getRotationQuaternion();
  75330. },
  75331. set: function (newRotation) {
  75332. this.setRotationQuaternion(newRotation);
  75333. },
  75334. enumerable: true,
  75335. configurable: true
  75336. });
  75337. Object.defineProperty(Bone.prototype, "scaling", {
  75338. get: function () {
  75339. return this.getScale();
  75340. },
  75341. set: function (newScaling) {
  75342. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  75343. },
  75344. enumerable: true,
  75345. configurable: true
  75346. });
  75347. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  75348. /**
  75349. * Gets the animation properties override
  75350. */
  75351. get: function () {
  75352. return this._skeleton.animationPropertiesOverride;
  75353. },
  75354. enumerable: true,
  75355. configurable: true
  75356. });
  75357. // Methods
  75358. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  75359. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75360. this._baseMatrix = matrix.clone();
  75361. this._localMatrix = matrix.clone();
  75362. this._skeleton._markAsDirty();
  75363. if (updateDifferenceMatrix) {
  75364. this._updateDifferenceMatrix();
  75365. }
  75366. };
  75367. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  75368. if (!rootMatrix) {
  75369. rootMatrix = this._baseMatrix;
  75370. }
  75371. if (this._parent) {
  75372. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75373. }
  75374. else {
  75375. this._absoluteTransform.copyFrom(rootMatrix);
  75376. }
  75377. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  75378. for (var index = 0; index < this.children.length; index++) {
  75379. this.children[index]._updateDifferenceMatrix();
  75380. }
  75381. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  75382. };
  75383. Bone.prototype.markAsDirty = function () {
  75384. this._currentRenderId++;
  75385. this._childRenderId++;
  75386. this._skeleton._markAsDirty();
  75387. };
  75388. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  75389. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75390. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  75391. // all animation may be coming from a library skeleton, so may need to create animation
  75392. if (this.animations.length === 0) {
  75393. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  75394. this.animations[0].setKeys([]);
  75395. }
  75396. // get animation info / verify there is such a range from the source bone
  75397. var sourceRange = source.animations[0].getRange(rangeName);
  75398. if (!sourceRange) {
  75399. return false;
  75400. }
  75401. var from = sourceRange.from;
  75402. var to = sourceRange.to;
  75403. var sourceKeys = source.animations[0].getKeys();
  75404. // rescaling prep
  75405. var sourceBoneLength = source.length;
  75406. var sourceParent = source.getParent();
  75407. var parent = this.getParent();
  75408. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  75409. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  75410. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  75411. var destKeys = this.animations[0].getKeys();
  75412. // loop vars declaration
  75413. var orig;
  75414. var origTranslation;
  75415. var mat;
  75416. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  75417. orig = sourceKeys[key];
  75418. if (orig.frame >= from && orig.frame <= to) {
  75419. if (rescaleAsRequired) {
  75420. mat = orig.value.clone();
  75421. // scale based on parent ratio, when bone has parent
  75422. if (parentScalingReqd) {
  75423. origTranslation = mat.getTranslation();
  75424. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  75425. // scale based on skeleton dimension ratio when root bone, and value is passed
  75426. }
  75427. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  75428. origTranslation = mat.getTranslation();
  75429. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  75430. // use original when root bone, and no data for skelDimensionsRatio
  75431. }
  75432. else {
  75433. mat = orig.value;
  75434. }
  75435. }
  75436. else {
  75437. mat = orig.value;
  75438. }
  75439. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  75440. }
  75441. }
  75442. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  75443. return true;
  75444. };
  75445. /**
  75446. * Translate the bone in local or world space.
  75447. * @param vec The amount to translate the bone.
  75448. * @param space The space that the translation is in.
  75449. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75450. */
  75451. Bone.prototype.translate = function (vec, space, mesh) {
  75452. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75453. var lm = this.getLocalMatrix();
  75454. if (space == BABYLON.Space.LOCAL) {
  75455. lm.m[12] += vec.x;
  75456. lm.m[13] += vec.y;
  75457. lm.m[14] += vec.z;
  75458. }
  75459. else {
  75460. var wm = null;
  75461. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75462. if (mesh) {
  75463. wm = mesh.getWorldMatrix();
  75464. }
  75465. this._skeleton.computeAbsoluteTransforms();
  75466. var tmat = Bone._tmpMats[0];
  75467. var tvec = Bone._tmpVecs[0];
  75468. if (this._parent) {
  75469. if (mesh && wm) {
  75470. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75471. tmat.multiplyToRef(wm, tmat);
  75472. }
  75473. else {
  75474. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75475. }
  75476. }
  75477. tmat.m[12] = 0;
  75478. tmat.m[13] = 0;
  75479. tmat.m[14] = 0;
  75480. tmat.invert();
  75481. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  75482. lm.m[12] += tvec.x;
  75483. lm.m[13] += tvec.y;
  75484. lm.m[14] += tvec.z;
  75485. }
  75486. this.markAsDirty();
  75487. };
  75488. /**
  75489. * Set the postion of the bone in local or world space.
  75490. * @param position The position to set the bone.
  75491. * @param space The space that the position is in.
  75492. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75493. */
  75494. Bone.prototype.setPosition = function (position, space, mesh) {
  75495. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75496. var lm = this.getLocalMatrix();
  75497. if (space == BABYLON.Space.LOCAL) {
  75498. lm.m[12] = position.x;
  75499. lm.m[13] = position.y;
  75500. lm.m[14] = position.z;
  75501. }
  75502. else {
  75503. var wm = null;
  75504. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75505. if (mesh) {
  75506. wm = mesh.getWorldMatrix();
  75507. }
  75508. this._skeleton.computeAbsoluteTransforms();
  75509. var tmat = Bone._tmpMats[0];
  75510. var vec = Bone._tmpVecs[0];
  75511. if (this._parent) {
  75512. if (mesh && wm) {
  75513. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75514. tmat.multiplyToRef(wm, tmat);
  75515. }
  75516. else {
  75517. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75518. }
  75519. }
  75520. tmat.invert();
  75521. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  75522. lm.m[12] = vec.x;
  75523. lm.m[13] = vec.y;
  75524. lm.m[14] = vec.z;
  75525. }
  75526. this.markAsDirty();
  75527. };
  75528. /**
  75529. * Set the absolute postion of the bone (world space).
  75530. * @param position The position to set the bone.
  75531. * @param mesh The mesh that this bone is attached to.
  75532. */
  75533. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  75534. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  75535. };
  75536. /**
  75537. * Set the scale of the bone on the x, y and z axes.
  75538. * @param x The scale of the bone on the x axis.
  75539. * @param x The scale of the bone on the y axis.
  75540. * @param z The scale of the bone on the z axis.
  75541. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75542. */
  75543. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  75544. if (scaleChildren === void 0) { scaleChildren = false; }
  75545. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  75546. if (!scaleChildren) {
  75547. this._negateScaleChildren.x = 1 / x;
  75548. this._negateScaleChildren.y = 1 / y;
  75549. this._negateScaleChildren.z = 1 / z;
  75550. }
  75551. this._syncScaleVector();
  75552. }
  75553. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  75554. };
  75555. /**
  75556. * Scale the bone on the x, y and z axes.
  75557. * @param x The amount to scale the bone on the x axis.
  75558. * @param x The amount to scale the bone on the y axis.
  75559. * @param z The amount to scale the bone on the z axis.
  75560. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75561. */
  75562. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  75563. if (scaleChildren === void 0) { scaleChildren = false; }
  75564. var locMat = this.getLocalMatrix();
  75565. var origLocMat = Bone._tmpMats[0];
  75566. origLocMat.copyFrom(locMat);
  75567. var origLocMatInv = Bone._tmpMats[1];
  75568. origLocMatInv.copyFrom(origLocMat);
  75569. origLocMatInv.invert();
  75570. var scaleMat = Bone._tmpMats[2];
  75571. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  75572. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  75573. this._scaleVector.x *= x;
  75574. this._scaleVector.y *= y;
  75575. this._scaleVector.z *= z;
  75576. locMat.multiplyToRef(origLocMatInv, locMat);
  75577. locMat.multiplyToRef(scaleMat, locMat);
  75578. locMat.multiplyToRef(origLocMat, locMat);
  75579. var parent = this.getParent();
  75580. if (parent) {
  75581. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  75582. }
  75583. else {
  75584. this.getAbsoluteTransform().copyFrom(locMat);
  75585. }
  75586. var len = this.children.length;
  75587. scaleMat.invert();
  75588. for (var i = 0; i < len; i++) {
  75589. var child = this.children[i];
  75590. var cm = child.getLocalMatrix();
  75591. cm.multiplyToRef(scaleMat, cm);
  75592. var lm = child.getLocalMatrix();
  75593. lm.m[12] *= x;
  75594. lm.m[13] *= y;
  75595. lm.m[14] *= z;
  75596. }
  75597. this.computeAbsoluteTransforms();
  75598. if (scaleChildren) {
  75599. for (var i = 0; i < len; i++) {
  75600. this.children[i].scale(x, y, z, scaleChildren);
  75601. }
  75602. }
  75603. this.markAsDirty();
  75604. };
  75605. /**
  75606. * Set the yaw, pitch, and roll of the bone in local or world space.
  75607. * @param yaw The rotation of the bone on the y axis.
  75608. * @param pitch The rotation of the bone on the x axis.
  75609. * @param roll The rotation of the bone on the z axis.
  75610. * @param space The space that the axes of rotation are in.
  75611. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75612. */
  75613. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  75614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75615. var rotMat = Bone._tmpMats[0];
  75616. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  75617. var rotMatInv = Bone._tmpMats[1];
  75618. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75619. rotMatInv.multiplyToRef(rotMat, rotMat);
  75620. this._rotateWithMatrix(rotMat, space, mesh);
  75621. };
  75622. /**
  75623. * Rotate the bone on an axis in local or world space.
  75624. * @param axis The axis to rotate the bone on.
  75625. * @param amount The amount to rotate the bone.
  75626. * @param space The space that the axis is in.
  75627. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75628. */
  75629. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  75630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75631. var rmat = Bone._tmpMats[0];
  75632. rmat.m[12] = 0;
  75633. rmat.m[13] = 0;
  75634. rmat.m[14] = 0;
  75635. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  75636. this._rotateWithMatrix(rmat, space, mesh);
  75637. };
  75638. /**
  75639. * Set the rotation of the bone to a particular axis angle in local or world space.
  75640. * @param axis The axis to rotate the bone on.
  75641. * @param angle The angle that the bone should be rotated to.
  75642. * @param space The space that the axis is in.
  75643. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75644. */
  75645. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  75646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75647. var rotMat = Bone._tmpMats[0];
  75648. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  75649. var rotMatInv = Bone._tmpMats[1];
  75650. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75651. rotMatInv.multiplyToRef(rotMat, rotMat);
  75652. this._rotateWithMatrix(rotMat, space, mesh);
  75653. };
  75654. /**
  75655. * Set the euler rotation of the bone in local of world space.
  75656. * @param rotation The euler rotation that the bone should be set to.
  75657. * @param space The space that the rotation is in.
  75658. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75659. */
  75660. Bone.prototype.setRotation = function (rotation, space, mesh) {
  75661. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75662. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  75663. };
  75664. /**
  75665. * Set the quaternion rotation of the bone in local of world space.
  75666. * @param quat The quaternion rotation that the bone should be set to.
  75667. * @param space The space that the rotation is in.
  75668. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75669. */
  75670. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  75671. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75672. var rotMatInv = Bone._tmpMats[0];
  75673. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75674. var rotMat = Bone._tmpMats[1];
  75675. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  75676. rotMatInv.multiplyToRef(rotMat, rotMat);
  75677. this._rotateWithMatrix(rotMat, space, mesh);
  75678. };
  75679. /**
  75680. * Set the rotation matrix of the bone in local of world space.
  75681. * @param rotMat The rotation matrix that the bone should be set to.
  75682. * @param space The space that the rotation is in.
  75683. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75684. */
  75685. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  75686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75687. var rotMatInv = Bone._tmpMats[0];
  75688. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75689. var rotMat2 = Bone._tmpMats[1];
  75690. rotMat2.copyFrom(rotMat);
  75691. rotMatInv.multiplyToRef(rotMat, rotMat2);
  75692. this._rotateWithMatrix(rotMat2, space, mesh);
  75693. };
  75694. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  75695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75696. var lmat = this.getLocalMatrix();
  75697. var lx = lmat.m[12];
  75698. var ly = lmat.m[13];
  75699. var lz = lmat.m[14];
  75700. var parent = this.getParent();
  75701. var parentScale = Bone._tmpMats[3];
  75702. var parentScaleInv = Bone._tmpMats[4];
  75703. if (parent) {
  75704. if (space == BABYLON.Space.WORLD) {
  75705. if (mesh) {
  75706. parentScale.copyFrom(mesh.getWorldMatrix());
  75707. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  75708. }
  75709. else {
  75710. parentScale.copyFrom(parent.getAbsoluteTransform());
  75711. }
  75712. }
  75713. else {
  75714. parentScale = parent._scaleMatrix;
  75715. }
  75716. parentScaleInv.copyFrom(parentScale);
  75717. parentScaleInv.invert();
  75718. lmat.multiplyToRef(parentScale, lmat);
  75719. lmat.multiplyToRef(rmat, lmat);
  75720. lmat.multiplyToRef(parentScaleInv, lmat);
  75721. }
  75722. else {
  75723. if (space == BABYLON.Space.WORLD && mesh) {
  75724. parentScale.copyFrom(mesh.getWorldMatrix());
  75725. parentScaleInv.copyFrom(parentScale);
  75726. parentScaleInv.invert();
  75727. lmat.multiplyToRef(parentScale, lmat);
  75728. lmat.multiplyToRef(rmat, lmat);
  75729. lmat.multiplyToRef(parentScaleInv, lmat);
  75730. }
  75731. else {
  75732. lmat.multiplyToRef(rmat, lmat);
  75733. }
  75734. }
  75735. lmat.m[12] = lx;
  75736. lmat.m[13] = ly;
  75737. lmat.m[14] = lz;
  75738. this.computeAbsoluteTransforms();
  75739. this.markAsDirty();
  75740. };
  75741. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  75742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75743. if (space == BABYLON.Space.WORLD) {
  75744. var scaleMatrix = Bone._tmpMats[2];
  75745. scaleMatrix.copyFrom(this._scaleMatrix);
  75746. rotMatInv.copyFrom(this.getAbsoluteTransform());
  75747. if (mesh) {
  75748. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  75749. var meshScale = Bone._tmpMats[3];
  75750. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  75751. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  75752. }
  75753. rotMatInv.invert();
  75754. scaleMatrix.m[0] *= this._scalingDeterminant;
  75755. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  75756. }
  75757. else {
  75758. rotMatInv.copyFrom(this.getLocalMatrix());
  75759. rotMatInv.invert();
  75760. var scaleMatrix = Bone._tmpMats[2];
  75761. scaleMatrix.copyFrom(this._scaleMatrix);
  75762. if (this._parent) {
  75763. var pscaleMatrix = Bone._tmpMats[3];
  75764. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  75765. pscaleMatrix.invert();
  75766. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  75767. }
  75768. else {
  75769. scaleMatrix.m[0] *= this._scalingDeterminant;
  75770. }
  75771. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  75772. }
  75773. };
  75774. /**
  75775. * Get the scale of the bone
  75776. * @returns the scale of the bone
  75777. */
  75778. Bone.prototype.getScale = function () {
  75779. return this._scaleVector.clone();
  75780. };
  75781. /**
  75782. * Copy the scale of the bone to a vector3.
  75783. * @param result The vector3 to copy the scale to
  75784. */
  75785. Bone.prototype.getScaleToRef = function (result) {
  75786. result.copyFrom(this._scaleVector);
  75787. };
  75788. /**
  75789. * Get the position of the bone in local or world space.
  75790. * @param space The space that the returned position is in.
  75791. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75792. * @returns The position of the bone
  75793. */
  75794. Bone.prototype.getPosition = function (space, mesh) {
  75795. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75796. if (mesh === void 0) { mesh = null; }
  75797. var pos = BABYLON.Vector3.Zero();
  75798. this.getPositionToRef(space, mesh, pos);
  75799. return pos;
  75800. };
  75801. /**
  75802. * Copy the position of the bone to a vector3 in local or world space.
  75803. * @param space The space that the returned position is in.
  75804. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75805. * @param result The vector3 to copy the position to.
  75806. */
  75807. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  75808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75809. if (space == BABYLON.Space.LOCAL) {
  75810. var lm = this.getLocalMatrix();
  75811. result.x = lm.m[12];
  75812. result.y = lm.m[13];
  75813. result.z = lm.m[14];
  75814. }
  75815. else {
  75816. var wm = null;
  75817. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75818. if (mesh) {
  75819. wm = mesh.getWorldMatrix();
  75820. }
  75821. this._skeleton.computeAbsoluteTransforms();
  75822. var tmat = Bone._tmpMats[0];
  75823. if (mesh && wm) {
  75824. tmat.copyFrom(this.getAbsoluteTransform());
  75825. tmat.multiplyToRef(wm, tmat);
  75826. }
  75827. else {
  75828. tmat = this.getAbsoluteTransform();
  75829. }
  75830. result.x = tmat.m[12];
  75831. result.y = tmat.m[13];
  75832. result.z = tmat.m[14];
  75833. }
  75834. };
  75835. /**
  75836. * Get the absolute position of the bone (world space).
  75837. * @param mesh The mesh that this bone is attached to.
  75838. * @returns The absolute position of the bone
  75839. */
  75840. Bone.prototype.getAbsolutePosition = function (mesh) {
  75841. if (mesh === void 0) { mesh = null; }
  75842. var pos = BABYLON.Vector3.Zero();
  75843. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  75844. return pos;
  75845. };
  75846. /**
  75847. * Copy the absolute position of the bone (world space) to the result param.
  75848. * @param mesh The mesh that this bone is attached to.
  75849. * @param result The vector3 to copy the absolute position to.
  75850. */
  75851. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  75852. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  75853. };
  75854. /**
  75855. * Compute the absolute transforms of this bone and its children.
  75856. */
  75857. Bone.prototype.computeAbsoluteTransforms = function () {
  75858. if (this._parent) {
  75859. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75860. }
  75861. else {
  75862. this._absoluteTransform.copyFrom(this._localMatrix);
  75863. var poseMatrix = this._skeleton.getPoseMatrix();
  75864. if (poseMatrix) {
  75865. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  75866. }
  75867. }
  75868. var children = this.children;
  75869. var len = children.length;
  75870. for (var i = 0; i < len; i++) {
  75871. children[i].computeAbsoluteTransforms();
  75872. }
  75873. };
  75874. Bone.prototype._syncScaleVector = function () {
  75875. var lm = this.getLocalMatrix();
  75876. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  75877. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  75878. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  75879. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  75880. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  75881. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  75882. this._scaleVector.x = xs * Math.sqrt(xsq);
  75883. this._scaleVector.y = ys * Math.sqrt(ysq);
  75884. this._scaleVector.z = zs * Math.sqrt(zsq);
  75885. if (this._parent) {
  75886. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  75887. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  75888. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  75889. }
  75890. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  75891. };
  75892. /**
  75893. * Get the world direction from an axis that is in the local space of the bone.
  75894. * @param localAxis The local direction that is used to compute the world direction.
  75895. * @param mesh The mesh that this bone is attached to.
  75896. * @returns The world direction
  75897. */
  75898. Bone.prototype.getDirection = function (localAxis, mesh) {
  75899. if (mesh === void 0) { mesh = null; }
  75900. var result = BABYLON.Vector3.Zero();
  75901. this.getDirectionToRef(localAxis, mesh, result);
  75902. return result;
  75903. };
  75904. /**
  75905. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  75906. * @param localAxis The local direction that is used to compute the world direction.
  75907. * @param mesh The mesh that this bone is attached to.
  75908. * @param result The vector3 that the world direction will be copied to.
  75909. */
  75910. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  75911. if (mesh === void 0) { mesh = null; }
  75912. var wm = null;
  75913. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75914. if (mesh) {
  75915. wm = mesh.getWorldMatrix();
  75916. }
  75917. this._skeleton.computeAbsoluteTransforms();
  75918. var mat = Bone._tmpMats[0];
  75919. mat.copyFrom(this.getAbsoluteTransform());
  75920. if (mesh && wm) {
  75921. mat.multiplyToRef(wm, mat);
  75922. }
  75923. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  75924. result.normalize();
  75925. };
  75926. /**
  75927. * Get the euler rotation of the bone in local or world space.
  75928. * @param space The space that the rotation should be in.
  75929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75930. * @returns The euler rotation
  75931. */
  75932. Bone.prototype.getRotation = function (space, mesh) {
  75933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75934. if (mesh === void 0) { mesh = null; }
  75935. var result = BABYLON.Vector3.Zero();
  75936. this.getRotationToRef(space, mesh, result);
  75937. return result;
  75938. };
  75939. /**
  75940. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  75941. * @param space The space that the rotation should be in.
  75942. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75943. * @param result The vector3 that the rotation should be copied to.
  75944. */
  75945. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  75946. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75947. if (mesh === void 0) { mesh = null; }
  75948. var quat = Bone._tmpQuat;
  75949. this.getRotationQuaternionToRef(space, mesh, quat);
  75950. quat.toEulerAnglesToRef(result);
  75951. };
  75952. /**
  75953. * Get the quaternion rotation of the bone in either local or world space.
  75954. * @param space The space that the rotation should be in.
  75955. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75956. * @returns The quaternion rotation
  75957. */
  75958. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  75959. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75960. if (mesh === void 0) { mesh = null; }
  75961. var result = BABYLON.Quaternion.Identity();
  75962. this.getRotationQuaternionToRef(space, mesh, result);
  75963. return result;
  75964. };
  75965. /**
  75966. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  75967. * @param space The space that the rotation should be in.
  75968. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75969. * @param result The quaternion that the rotation should be copied to.
  75970. */
  75971. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  75972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75973. if (mesh === void 0) { mesh = null; }
  75974. if (space == BABYLON.Space.LOCAL) {
  75975. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  75976. }
  75977. else {
  75978. var mat = Bone._tmpMats[0];
  75979. var amat = this.getAbsoluteTransform();
  75980. if (mesh) {
  75981. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  75982. }
  75983. else {
  75984. mat.copyFrom(amat);
  75985. }
  75986. mat.m[0] *= this._scalingDeterminant;
  75987. mat.m[1] *= this._scalingDeterminant;
  75988. mat.m[2] *= this._scalingDeterminant;
  75989. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  75990. }
  75991. };
  75992. /**
  75993. * Get the rotation matrix of the bone in local or world space.
  75994. * @param space The space that the rotation should be in.
  75995. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75996. * @returns The rotation matrix
  75997. */
  75998. Bone.prototype.getRotationMatrix = function (space, mesh) {
  75999. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76000. var result = BABYLON.Matrix.Identity();
  76001. this.getRotationMatrixToRef(space, mesh, result);
  76002. return result;
  76003. };
  76004. /**
  76005. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  76006. * @param space The space that the rotation should be in.
  76007. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76008. * @param result The quaternion that the rotation should be copied to.
  76009. */
  76010. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  76011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76012. if (space == BABYLON.Space.LOCAL) {
  76013. this.getLocalMatrix().getRotationMatrixToRef(result);
  76014. }
  76015. else {
  76016. var mat = Bone._tmpMats[0];
  76017. var amat = this.getAbsoluteTransform();
  76018. if (mesh) {
  76019. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76020. }
  76021. else {
  76022. mat.copyFrom(amat);
  76023. }
  76024. mat.m[0] *= this._scalingDeterminant;
  76025. mat.m[1] *= this._scalingDeterminant;
  76026. mat.m[2] *= this._scalingDeterminant;
  76027. mat.getRotationMatrixToRef(result);
  76028. }
  76029. };
  76030. /**
  76031. * Get the world position of a point that is in the local space of the bone.
  76032. * @param position The local position
  76033. * @param mesh The mesh that this bone is attached to.
  76034. * @returns The world position
  76035. */
  76036. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  76037. if (mesh === void 0) { mesh = null; }
  76038. var result = BABYLON.Vector3.Zero();
  76039. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  76040. return result;
  76041. };
  76042. /**
  76043. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  76044. * @param position The local position
  76045. * @param mesh The mesh that this bone is attached to.
  76046. * @param result The vector3 that the world position should be copied to.
  76047. */
  76048. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  76049. if (mesh === void 0) { mesh = null; }
  76050. var wm = null;
  76051. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76052. if (mesh) {
  76053. wm = mesh.getWorldMatrix();
  76054. }
  76055. this._skeleton.computeAbsoluteTransforms();
  76056. var tmat = Bone._tmpMats[0];
  76057. if (mesh && wm) {
  76058. tmat.copyFrom(this.getAbsoluteTransform());
  76059. tmat.multiplyToRef(wm, tmat);
  76060. }
  76061. else {
  76062. tmat = this.getAbsoluteTransform();
  76063. }
  76064. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76065. };
  76066. /**
  76067. * Get the local position of a point that is in world space.
  76068. * @param position The world position
  76069. * @param mesh The mesh that this bone is attached to.
  76070. * @returns The local position
  76071. */
  76072. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  76073. if (mesh === void 0) { mesh = null; }
  76074. var result = BABYLON.Vector3.Zero();
  76075. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  76076. return result;
  76077. };
  76078. /**
  76079. * Get the local position of a point that is in world space and copy it to the result param.
  76080. * @param position The world position
  76081. * @param mesh The mesh that this bone is attached to.
  76082. * @param result The vector3 that the local position should be copied to.
  76083. */
  76084. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76085. if (mesh === void 0) { mesh = null; }
  76086. var wm = null;
  76087. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76088. if (mesh) {
  76089. wm = mesh.getWorldMatrix();
  76090. }
  76091. this._skeleton.computeAbsoluteTransforms();
  76092. var tmat = Bone._tmpMats[0];
  76093. tmat.copyFrom(this.getAbsoluteTransform());
  76094. if (mesh && wm) {
  76095. tmat.multiplyToRef(wm, tmat);
  76096. }
  76097. tmat.invert();
  76098. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76099. };
  76100. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76101. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  76102. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76103. return Bone;
  76104. }(BABYLON.Node));
  76105. BABYLON.Bone = Bone;
  76106. })(BABYLON || (BABYLON = {}));
  76107. //# sourceMappingURL=babylon.bone.js.map
  76108. "use strict";
  76109. var BABYLON;
  76110. (function (BABYLON) {
  76111. var BoneIKController = /** @class */ (function () {
  76112. function BoneIKController(mesh, bone, options) {
  76113. this.targetPosition = BABYLON.Vector3.Zero();
  76114. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76115. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76116. this.poleAngle = 0;
  76117. this.slerpAmount = 1;
  76118. this._bone1Quat = BABYLON.Quaternion.Identity();
  76119. this._bone1Mat = BABYLON.Matrix.Identity();
  76120. this._bone2Ang = Math.PI;
  76121. this._maxAngle = Math.PI;
  76122. this._rightHandedSystem = false;
  76123. this._bendAxis = BABYLON.Vector3.Right();
  76124. this._slerping = false;
  76125. this._adjustRoll = 0;
  76126. this._bone2 = bone;
  76127. this._bone1 = bone.getParent();
  76128. if (!this._bone1) {
  76129. return;
  76130. }
  76131. this.mesh = mesh;
  76132. var bonePos = bone.getPosition();
  76133. if (bone.getAbsoluteTransform().determinant() > 0) {
  76134. this._rightHandedSystem = true;
  76135. this._bendAxis.x = 0;
  76136. this._bendAxis.y = 0;
  76137. this._bendAxis.z = -1;
  76138. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76139. this._adjustRoll = Math.PI * .5;
  76140. this._bendAxis.z = 1;
  76141. }
  76142. }
  76143. if (this._bone1.length) {
  76144. var boneScale1 = this._bone1.getScale();
  76145. var boneScale2 = this._bone2.getScale();
  76146. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76147. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76148. }
  76149. else if (this._bone1.children[0]) {
  76150. mesh.computeWorldMatrix(true);
  76151. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76152. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76153. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76154. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76155. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76156. }
  76157. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76158. this.maxAngle = Math.PI;
  76159. if (options) {
  76160. if (options.targetMesh) {
  76161. this.targetMesh = options.targetMesh;
  76162. this.targetMesh.computeWorldMatrix(true);
  76163. }
  76164. if (options.poleTargetMesh) {
  76165. this.poleTargetMesh = options.poleTargetMesh;
  76166. this.poleTargetMesh.computeWorldMatrix(true);
  76167. }
  76168. else if (options.poleTargetBone) {
  76169. this.poleTargetBone = options.poleTargetBone;
  76170. }
  76171. else if (this._bone1.getParent()) {
  76172. this.poleTargetBone = this._bone1.getParent();
  76173. }
  76174. if (options.poleTargetLocalOffset) {
  76175. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76176. }
  76177. if (options.poleAngle) {
  76178. this.poleAngle = options.poleAngle;
  76179. }
  76180. if (options.bendAxis) {
  76181. this._bendAxis.copyFrom(options.bendAxis);
  76182. }
  76183. if (options.maxAngle) {
  76184. this.maxAngle = options.maxAngle;
  76185. }
  76186. if (options.slerpAmount) {
  76187. this.slerpAmount = options.slerpAmount;
  76188. }
  76189. }
  76190. }
  76191. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76192. get: function () {
  76193. return this._maxAngle;
  76194. },
  76195. set: function (value) {
  76196. this._setMaxAngle(value);
  76197. },
  76198. enumerable: true,
  76199. configurable: true
  76200. });
  76201. BoneIKController.prototype._setMaxAngle = function (ang) {
  76202. if (ang < 0) {
  76203. ang = 0;
  76204. }
  76205. if (ang > Math.PI || ang == undefined) {
  76206. ang = Math.PI;
  76207. }
  76208. this._maxAngle = ang;
  76209. var a = this._bone1Length;
  76210. var b = this._bone2Length;
  76211. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76212. };
  76213. BoneIKController.prototype.update = function () {
  76214. var bone1 = this._bone1;
  76215. if (!bone1) {
  76216. return;
  76217. }
  76218. var target = this.targetPosition;
  76219. var poleTarget = this.poleTargetPosition;
  76220. var mat1 = BoneIKController._tmpMats[0];
  76221. var mat2 = BoneIKController._tmpMats[1];
  76222. if (this.targetMesh) {
  76223. target.copyFrom(this.targetMesh.getAbsolutePosition());
  76224. }
  76225. if (this.poleTargetBone) {
  76226. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  76227. }
  76228. else if (this.poleTargetMesh) {
  76229. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  76230. }
  76231. var bonePos = BoneIKController._tmpVecs[0];
  76232. var zaxis = BoneIKController._tmpVecs[1];
  76233. var xaxis = BoneIKController._tmpVecs[2];
  76234. var yaxis = BoneIKController._tmpVecs[3];
  76235. var upAxis = BoneIKController._tmpVecs[4];
  76236. var _tmpQuat = BoneIKController._tmpQuat;
  76237. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  76238. poleTarget.subtractToRef(bonePos, upAxis);
  76239. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  76240. upAxis.y = 1;
  76241. }
  76242. else {
  76243. upAxis.normalize();
  76244. }
  76245. target.subtractToRef(bonePos, yaxis);
  76246. yaxis.normalize();
  76247. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  76248. zaxis.normalize();
  76249. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  76250. xaxis.normalize();
  76251. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  76252. var a = this._bone1Length;
  76253. var b = this._bone2Length;
  76254. var c = BABYLON.Vector3.Distance(bonePos, target);
  76255. if (this._maxReach > 0) {
  76256. c = Math.min(this._maxReach, c);
  76257. }
  76258. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  76259. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  76260. if (acosa > 1) {
  76261. acosa = 1;
  76262. }
  76263. if (acosb > 1) {
  76264. acosb = 1;
  76265. }
  76266. if (acosa < -1) {
  76267. acosa = -1;
  76268. }
  76269. if (acosb < -1) {
  76270. acosb = -1;
  76271. }
  76272. var angA = Math.acos(acosa);
  76273. var angB = Math.acos(acosb);
  76274. var angC = -angA - angB;
  76275. if (this._rightHandedSystem) {
  76276. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  76277. mat2.multiplyToRef(mat1, mat1);
  76278. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  76279. mat2.multiplyToRef(mat1, mat1);
  76280. }
  76281. else {
  76282. var _tmpVec = BoneIKController._tmpVecs[5];
  76283. _tmpVec.copyFrom(this._bendAxis);
  76284. _tmpVec.x *= -1;
  76285. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  76286. mat2.multiplyToRef(mat1, mat1);
  76287. }
  76288. if (this.poleAngle) {
  76289. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  76290. mat1.multiplyToRef(mat2, mat1);
  76291. }
  76292. if (this._bone1) {
  76293. if (this.slerpAmount < 1) {
  76294. if (!this._slerping) {
  76295. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  76296. }
  76297. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  76298. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  76299. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  76300. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  76301. this._slerping = true;
  76302. }
  76303. else {
  76304. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  76305. this._bone1Mat.copyFrom(mat1);
  76306. this._slerping = false;
  76307. }
  76308. }
  76309. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  76310. this._bone2Ang = angC;
  76311. };
  76312. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76313. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  76314. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76315. return BoneIKController;
  76316. }());
  76317. BABYLON.BoneIKController = BoneIKController;
  76318. })(BABYLON || (BABYLON = {}));
  76319. //# sourceMappingURL=babylon.boneIKController.js.map
  76320. "use strict";
  76321. var BABYLON;
  76322. (function (BABYLON) {
  76323. var BoneLookController = /** @class */ (function () {
  76324. /**
  76325. * Create a BoneLookController
  76326. * @param mesh the mesh that the bone belongs to
  76327. * @param bone the bone that will be looking to the target
  76328. * @param target the target Vector3 to look at
  76329. * @param settings optional settings:
  76330. * - maxYaw: the maximum angle the bone will yaw to
  76331. * - minYaw: the minimum angle the bone will yaw to
  76332. * - maxPitch: the maximum angle the bone will pitch to
  76333. * - minPitch: the minimum angle the bone will yaw to
  76334. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  76335. * - upAxis: the up axis of the coordinate system
  76336. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76337. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  76338. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  76339. * - adjustYaw: used to make an adjustment to the yaw of the bone
  76340. * - adjustPitch: used to make an adjustment to the pitch of the bone
  76341. * - adjustRoll: used to make an adjustment to the roll of the bone
  76342. **/
  76343. function BoneLookController(mesh, bone, target, options) {
  76344. /**
  76345. * The up axis of the coordinate system that is used when the bone is rotated.
  76346. */
  76347. this.upAxis = BABYLON.Vector3.Up();
  76348. /**
  76349. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76350. */
  76351. this.upAxisSpace = BABYLON.Space.LOCAL;
  76352. /**
  76353. * Used to make an adjustment to the yaw of the bone.
  76354. */
  76355. this.adjustYaw = 0;
  76356. /**
  76357. * Used to make an adjustment to the pitch of the bone.
  76358. */
  76359. this.adjustPitch = 0;
  76360. /**
  76361. * Used to make an adjustment to the roll of the bone.
  76362. */
  76363. this.adjustRoll = 0;
  76364. /**
  76365. * 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).
  76366. */
  76367. this.slerpAmount = 1;
  76368. this._boneQuat = BABYLON.Quaternion.Identity();
  76369. this._slerping = false;
  76370. this._firstFrameSkipped = false;
  76371. this._fowardAxis = BABYLON.Vector3.Forward();
  76372. this.mesh = mesh;
  76373. this.bone = bone;
  76374. this.target = target;
  76375. if (options) {
  76376. if (options.adjustYaw) {
  76377. this.adjustYaw = options.adjustYaw;
  76378. }
  76379. if (options.adjustPitch) {
  76380. this.adjustPitch = options.adjustPitch;
  76381. }
  76382. if (options.adjustRoll) {
  76383. this.adjustRoll = options.adjustRoll;
  76384. }
  76385. if (options.maxYaw != null) {
  76386. this.maxYaw = options.maxYaw;
  76387. }
  76388. else {
  76389. this.maxYaw = Math.PI;
  76390. }
  76391. if (options.minYaw != null) {
  76392. this.minYaw = options.minYaw;
  76393. }
  76394. else {
  76395. this.minYaw = -Math.PI;
  76396. }
  76397. if (options.maxPitch != null) {
  76398. this.maxPitch = options.maxPitch;
  76399. }
  76400. else {
  76401. this.maxPitch = Math.PI;
  76402. }
  76403. if (options.minPitch != null) {
  76404. this.minPitch = options.minPitch;
  76405. }
  76406. else {
  76407. this.minPitch = -Math.PI;
  76408. }
  76409. if (options.slerpAmount != null) {
  76410. this.slerpAmount = options.slerpAmount;
  76411. }
  76412. if (options.upAxis != null) {
  76413. this.upAxis = options.upAxis;
  76414. }
  76415. if (options.upAxisSpace != null) {
  76416. this.upAxisSpace = options.upAxisSpace;
  76417. }
  76418. if (options.yawAxis != null || options.pitchAxis != null) {
  76419. var newYawAxis = BABYLON.Axis.Y;
  76420. var newPitchAxis = BABYLON.Axis.X;
  76421. if (options.yawAxis != null) {
  76422. newYawAxis = options.yawAxis.clone();
  76423. newYawAxis.normalize();
  76424. }
  76425. if (options.pitchAxis != null) {
  76426. newPitchAxis = options.pitchAxis.clone();
  76427. newPitchAxis.normalize();
  76428. }
  76429. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  76430. this._transformYawPitch = BABYLON.Matrix.Identity();
  76431. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  76432. this._transformYawPitchInv = this._transformYawPitch.clone();
  76433. this._transformYawPitch.invert();
  76434. }
  76435. }
  76436. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  76437. this.upAxisSpace = BABYLON.Space.LOCAL;
  76438. }
  76439. }
  76440. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  76441. /**
  76442. * Get/set the minimum yaw angle that the bone can look to.
  76443. */
  76444. get: function () {
  76445. return this._minYaw;
  76446. },
  76447. set: function (value) {
  76448. this._minYaw = value;
  76449. this._minYawSin = Math.sin(value);
  76450. this._minYawCos = Math.cos(value);
  76451. if (this._maxYaw != null) {
  76452. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76453. this._yawRange = this._maxYaw - this._minYaw;
  76454. }
  76455. },
  76456. enumerable: true,
  76457. configurable: true
  76458. });
  76459. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  76460. /**
  76461. * Get/set the maximum yaw angle that the bone can look to.
  76462. */
  76463. get: function () {
  76464. return this._maxYaw;
  76465. },
  76466. set: function (value) {
  76467. this._maxYaw = value;
  76468. this._maxYawSin = Math.sin(value);
  76469. this._maxYawCos = Math.cos(value);
  76470. if (this._minYaw != null) {
  76471. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76472. this._yawRange = this._maxYaw - this._minYaw;
  76473. }
  76474. },
  76475. enumerable: true,
  76476. configurable: true
  76477. });
  76478. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  76479. /**
  76480. * Get/set the minimum pitch angle that the bone can look to.
  76481. */
  76482. get: function () {
  76483. return this._minPitch;
  76484. },
  76485. set: function (value) {
  76486. this._minPitch = value;
  76487. this._minPitchTan = Math.tan(value);
  76488. },
  76489. enumerable: true,
  76490. configurable: true
  76491. });
  76492. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  76493. /**
  76494. * Get/set the maximum pitch angle that the bone can look to.
  76495. */
  76496. get: function () {
  76497. return this._maxPitch;
  76498. },
  76499. set: function (value) {
  76500. this._maxPitch = value;
  76501. this._maxPitchTan = Math.tan(value);
  76502. },
  76503. enumerable: true,
  76504. configurable: true
  76505. });
  76506. /**
  76507. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  76508. */
  76509. BoneLookController.prototype.update = function () {
  76510. //skip the first frame when slerping so that the mesh rotation is correct
  76511. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  76512. this._firstFrameSkipped = true;
  76513. return;
  76514. }
  76515. var bone = this.bone;
  76516. var bonePos = BoneLookController._tmpVecs[0];
  76517. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  76518. var target = this.target;
  76519. var _tmpMat1 = BoneLookController._tmpMats[0];
  76520. var _tmpMat2 = BoneLookController._tmpMats[1];
  76521. var mesh = this.mesh;
  76522. var parentBone = bone.getParent();
  76523. var upAxis = BoneLookController._tmpVecs[1];
  76524. upAxis.copyFrom(this.upAxis);
  76525. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  76526. if (this._transformYawPitch) {
  76527. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  76528. }
  76529. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  76530. }
  76531. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  76532. mesh.getDirectionToRef(upAxis, upAxis);
  76533. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  76534. upAxis.normalize();
  76535. }
  76536. }
  76537. var checkYaw = false;
  76538. var checkPitch = false;
  76539. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  76540. checkYaw = true;
  76541. }
  76542. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  76543. checkPitch = true;
  76544. }
  76545. if (checkYaw || checkPitch) {
  76546. var spaceMat = BoneLookController._tmpMats[2];
  76547. var spaceMatInv = BoneLookController._tmpMats[3];
  76548. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  76549. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  76550. }
  76551. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  76552. spaceMat.copyFrom(mesh.getWorldMatrix());
  76553. }
  76554. else {
  76555. var forwardAxis = BoneLookController._tmpVecs[2];
  76556. forwardAxis.copyFrom(this._fowardAxis);
  76557. if (this._transformYawPitch) {
  76558. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  76559. }
  76560. if (parentBone) {
  76561. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  76562. }
  76563. else {
  76564. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  76565. }
  76566. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  76567. rightAxis.normalize();
  76568. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  76569. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  76570. }
  76571. spaceMat.invertToRef(spaceMatInv);
  76572. var xzlen = null;
  76573. if (checkPitch) {
  76574. var localTarget = BoneLookController._tmpVecs[3];
  76575. target.subtractToRef(bonePos, localTarget);
  76576. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76577. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76578. var pitch = Math.atan2(localTarget.y, xzlen);
  76579. var newPitch = pitch;
  76580. if (pitch > this._maxPitch) {
  76581. localTarget.y = this._maxPitchTan * xzlen;
  76582. newPitch = this._maxPitch;
  76583. }
  76584. else if (pitch < this._minPitch) {
  76585. localTarget.y = this._minPitchTan * xzlen;
  76586. newPitch = this._minPitch;
  76587. }
  76588. if (pitch != newPitch) {
  76589. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76590. localTarget.addInPlace(bonePos);
  76591. target = localTarget;
  76592. }
  76593. }
  76594. if (checkYaw) {
  76595. var localTarget = BoneLookController._tmpVecs[4];
  76596. target.subtractToRef(bonePos, localTarget);
  76597. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76598. var yaw = Math.atan2(localTarget.x, localTarget.z);
  76599. var newYaw = yaw;
  76600. if (yaw > this._maxYaw || yaw < this._minYaw) {
  76601. if (xzlen == null) {
  76602. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76603. }
  76604. if (this._yawRange > Math.PI) {
  76605. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  76606. localTarget.z = this._maxYawCos * xzlen;
  76607. localTarget.x = this._maxYawSin * xzlen;
  76608. newYaw = this._maxYaw;
  76609. }
  76610. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  76611. localTarget.z = this._minYawCos * xzlen;
  76612. localTarget.x = this._minYawSin * xzlen;
  76613. newYaw = this._minYaw;
  76614. }
  76615. }
  76616. else {
  76617. if (yaw > this._maxYaw) {
  76618. localTarget.z = this._maxYawCos * xzlen;
  76619. localTarget.x = this._maxYawSin * xzlen;
  76620. newYaw = this._maxYaw;
  76621. }
  76622. else if (yaw < this._minYaw) {
  76623. localTarget.z = this._minYawCos * xzlen;
  76624. localTarget.x = this._minYawSin * xzlen;
  76625. newYaw = this._minYaw;
  76626. }
  76627. }
  76628. }
  76629. if (this._slerping && this._yawRange > Math.PI) {
  76630. //are we going to be crossing into the min/max region?
  76631. var boneFwd = BoneLookController._tmpVecs[8];
  76632. boneFwd.copyFrom(BABYLON.Axis.Z);
  76633. if (this._transformYawPitch) {
  76634. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  76635. }
  76636. var boneRotMat = BoneLookController._tmpMats[4];
  76637. this._boneQuat.toRotationMatrix(boneRotMat);
  76638. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  76639. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  76640. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  76641. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  76642. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  76643. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  76644. if (angBtwTar > angBtwMidYaw) {
  76645. if (xzlen == null) {
  76646. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76647. }
  76648. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  76649. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  76650. if (angBtwMin < angBtwMax) {
  76651. newYaw = boneYaw + Math.PI * .75;
  76652. localTarget.z = Math.cos(newYaw) * xzlen;
  76653. localTarget.x = Math.sin(newYaw) * xzlen;
  76654. }
  76655. else {
  76656. newYaw = boneYaw - Math.PI * .75;
  76657. localTarget.z = Math.cos(newYaw) * xzlen;
  76658. localTarget.x = Math.sin(newYaw) * xzlen;
  76659. }
  76660. }
  76661. }
  76662. if (yaw != newYaw) {
  76663. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76664. localTarget.addInPlace(bonePos);
  76665. target = localTarget;
  76666. }
  76667. }
  76668. }
  76669. var zaxis = BoneLookController._tmpVecs[5];
  76670. var xaxis = BoneLookController._tmpVecs[6];
  76671. var yaxis = BoneLookController._tmpVecs[7];
  76672. var _tmpQuat = BoneLookController._tmpQuat;
  76673. target.subtractToRef(bonePos, zaxis);
  76674. zaxis.normalize();
  76675. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  76676. xaxis.normalize();
  76677. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  76678. yaxis.normalize();
  76679. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  76680. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  76681. return;
  76682. }
  76683. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  76684. return;
  76685. }
  76686. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  76687. return;
  76688. }
  76689. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  76690. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  76691. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  76692. }
  76693. if (this.slerpAmount < 1) {
  76694. if (!this._slerping) {
  76695. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  76696. }
  76697. if (this._transformYawPitch) {
  76698. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  76699. }
  76700. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  76701. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  76702. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  76703. this._slerping = true;
  76704. }
  76705. else {
  76706. if (this._transformYawPitch) {
  76707. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  76708. }
  76709. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  76710. this._slerping = false;
  76711. }
  76712. };
  76713. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  76714. var angDiff = ang2 - ang1;
  76715. angDiff %= Math.PI * 2;
  76716. if (angDiff > Math.PI) {
  76717. angDiff -= Math.PI * 2;
  76718. }
  76719. else if (angDiff < -Math.PI) {
  76720. angDiff += Math.PI * 2;
  76721. }
  76722. return angDiff;
  76723. };
  76724. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  76725. ang1 %= (2 * Math.PI);
  76726. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  76727. ang2 %= (2 * Math.PI);
  76728. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  76729. var ab = 0;
  76730. if (ang1 < ang2) {
  76731. ab = ang2 - ang1;
  76732. }
  76733. else {
  76734. ab = ang1 - ang2;
  76735. }
  76736. if (ab > Math.PI) {
  76737. ab = Math.PI * 2 - ab;
  76738. }
  76739. return ab;
  76740. };
  76741. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  76742. ang %= (2 * Math.PI);
  76743. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  76744. ang1 %= (2 * Math.PI);
  76745. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  76746. ang2 %= (2 * Math.PI);
  76747. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  76748. if (ang1 < ang2) {
  76749. if (ang > ang1 && ang < ang2) {
  76750. return true;
  76751. }
  76752. }
  76753. else {
  76754. if (ang > ang2 && ang < ang1) {
  76755. return true;
  76756. }
  76757. }
  76758. return false;
  76759. };
  76760. 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()];
  76761. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  76762. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76763. return BoneLookController;
  76764. }());
  76765. BABYLON.BoneLookController = BoneLookController;
  76766. })(BABYLON || (BABYLON = {}));
  76767. //# sourceMappingURL=babylon.boneLookController.js.map
  76768. "use strict";
  76769. var BABYLON;
  76770. (function (BABYLON) {
  76771. var Skeleton = /** @class */ (function () {
  76772. function Skeleton(name, id, scene) {
  76773. this.name = name;
  76774. this.id = id;
  76775. this.bones = new Array();
  76776. this.needInitialSkinMatrix = false;
  76777. this._isDirty = true;
  76778. this._meshesWithPoseMatrix = new Array();
  76779. this._identity = BABYLON.Matrix.Identity();
  76780. this._ranges = {};
  76781. this._lastAbsoluteTransformsUpdateId = -1;
  76782. /**
  76783. * Specifies if the skeleton should be serialized.
  76784. */
  76785. this.doNotSerialize = false;
  76786. // Events
  76787. /**
  76788. * An event triggered before computing the skeleton's matrices
  76789. */
  76790. this.onBeforeComputeObservable = new BABYLON.Observable();
  76791. this.bones = [];
  76792. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76793. scene.skeletons.push(this);
  76794. //make sure it will recalculate the matrix next time prepare is called.
  76795. this._isDirty = true;
  76796. }
  76797. // Members
  76798. Skeleton.prototype.getTransformMatrices = function (mesh) {
  76799. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  76800. return mesh._bonesTransformMatrices;
  76801. }
  76802. if (!this._transformMatrices) {
  76803. this.prepare();
  76804. }
  76805. return this._transformMatrices;
  76806. };
  76807. Skeleton.prototype.getScene = function () {
  76808. return this._scene;
  76809. };
  76810. // Methods
  76811. /**
  76812. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  76813. */
  76814. Skeleton.prototype.toString = function (fullDetails) {
  76815. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  76816. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  76817. if (fullDetails) {
  76818. ret += ", Ranges: {";
  76819. var first = true;
  76820. for (var name_1 in this._ranges) {
  76821. if (first) {
  76822. ret += ", ";
  76823. first = false;
  76824. }
  76825. ret += name_1;
  76826. }
  76827. ret += "}";
  76828. }
  76829. return ret;
  76830. };
  76831. /**
  76832. * Get bone's index searching by name
  76833. * @param {string} name is bone's name to search for
  76834. * @return {number} Indice of the bone. Returns -1 if not found
  76835. */
  76836. Skeleton.prototype.getBoneIndexByName = function (name) {
  76837. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  76838. if (this.bones[boneIndex].name === name) {
  76839. return boneIndex;
  76840. }
  76841. }
  76842. return -1;
  76843. };
  76844. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  76845. // check name not already in use
  76846. if (!this._ranges[name]) {
  76847. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  76848. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76849. if (this.bones[i].animations[0]) {
  76850. this.bones[i].animations[0].createRange(name, from, to);
  76851. }
  76852. }
  76853. }
  76854. };
  76855. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  76856. if (deleteFrames === void 0) { deleteFrames = true; }
  76857. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76858. if (this.bones[i].animations[0]) {
  76859. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  76860. }
  76861. }
  76862. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  76863. };
  76864. Skeleton.prototype.getAnimationRange = function (name) {
  76865. return this._ranges[name];
  76866. };
  76867. /**
  76868. * Returns as an Array, all AnimationRanges defined on this skeleton
  76869. */
  76870. Skeleton.prototype.getAnimationRanges = function () {
  76871. var animationRanges = [];
  76872. var name;
  76873. var i = 0;
  76874. for (name in this._ranges) {
  76875. animationRanges[i] = this._ranges[name];
  76876. i++;
  76877. }
  76878. return animationRanges;
  76879. };
  76880. /**
  76881. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  76882. */
  76883. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  76884. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76885. if (this._ranges[name] || !source.getAnimationRange(name)) {
  76886. return false;
  76887. }
  76888. var ret = true;
  76889. var frameOffset = this._getHighestAnimationFrame() + 1;
  76890. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  76891. var boneDict = {};
  76892. var sourceBones = source.bones;
  76893. var nBones;
  76894. var i;
  76895. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  76896. boneDict[sourceBones[i].name] = sourceBones[i];
  76897. }
  76898. if (this.bones.length !== sourceBones.length) {
  76899. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  76900. ret = false;
  76901. }
  76902. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  76903. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  76904. var boneName = this.bones[i].name;
  76905. var sourceBone = boneDict[boneName];
  76906. if (sourceBone) {
  76907. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  76908. }
  76909. else {
  76910. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  76911. ret = false;
  76912. }
  76913. }
  76914. // do not call createAnimationRange(), since it also is done to bones, which was already done
  76915. var range = source.getAnimationRange(name);
  76916. if (range) {
  76917. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  76918. }
  76919. return ret;
  76920. };
  76921. Skeleton.prototype.returnToRest = function () {
  76922. for (var index = 0; index < this.bones.length; index++) {
  76923. this.bones[index].returnToRest();
  76924. }
  76925. };
  76926. Skeleton.prototype._getHighestAnimationFrame = function () {
  76927. var ret = 0;
  76928. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76929. if (this.bones[i].animations[0]) {
  76930. var highest = this.bones[i].animations[0].getHighestFrame();
  76931. if (ret < highest) {
  76932. ret = highest;
  76933. }
  76934. }
  76935. }
  76936. return ret;
  76937. };
  76938. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  76939. var range = this.getAnimationRange(name);
  76940. if (!range) {
  76941. return null;
  76942. }
  76943. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  76944. };
  76945. Skeleton.prototype._markAsDirty = function () {
  76946. this._isDirty = true;
  76947. };
  76948. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  76949. this._meshesWithPoseMatrix.push(mesh);
  76950. };
  76951. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  76952. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  76953. if (index > -1) {
  76954. this._meshesWithPoseMatrix.splice(index, 1);
  76955. }
  76956. };
  76957. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  76958. this.onBeforeComputeObservable.notifyObservers(this);
  76959. for (var index = 0; index < this.bones.length; index++) {
  76960. var bone = this.bones[index];
  76961. var parentBone = bone.getParent();
  76962. if (parentBone) {
  76963. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  76964. }
  76965. else {
  76966. if (initialSkinMatrix) {
  76967. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  76968. }
  76969. else {
  76970. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  76971. }
  76972. }
  76973. if (bone._index !== -1) {
  76974. var mappedIndex = bone._index === null ? index : bone._index;
  76975. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  76976. }
  76977. }
  76978. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  76979. };
  76980. Skeleton.prototype.prepare = function () {
  76981. if (!this._isDirty) {
  76982. return;
  76983. }
  76984. if (this.needInitialSkinMatrix) {
  76985. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  76986. var mesh = this._meshesWithPoseMatrix[index];
  76987. var poseMatrix = mesh.getPoseMatrix();
  76988. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  76989. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  76990. }
  76991. if (this._synchronizedWithMesh !== mesh) {
  76992. this._synchronizedWithMesh = mesh;
  76993. // Prepare bones
  76994. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  76995. var bone = this.bones[boneIndex];
  76996. if (!bone.getParent()) {
  76997. var matrix = bone.getBaseMatrix();
  76998. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  76999. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77000. }
  77001. }
  77002. }
  77003. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77004. }
  77005. }
  77006. else {
  77007. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77008. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77009. }
  77010. this._computeTransformMatrices(this._transformMatrices, null);
  77011. }
  77012. this._isDirty = false;
  77013. this._scene._activeBones.addCount(this.bones.length, false);
  77014. };
  77015. Skeleton.prototype.getAnimatables = function () {
  77016. if (!this._animatables || this._animatables.length !== this.bones.length) {
  77017. this._animatables = [];
  77018. for (var index = 0; index < this.bones.length; index++) {
  77019. this._animatables.push(this.bones[index]);
  77020. }
  77021. }
  77022. return this._animatables;
  77023. };
  77024. Skeleton.prototype.clone = function (name, id) {
  77025. var result = new Skeleton(name, id || name, this._scene);
  77026. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77027. for (var index = 0; index < this.bones.length; index++) {
  77028. var source = this.bones[index];
  77029. var parentBone = null;
  77030. var parent_1 = source.getParent();
  77031. if (parent_1) {
  77032. var parentIndex = this.bones.indexOf(parent_1);
  77033. parentBone = result.bones[parentIndex];
  77034. }
  77035. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  77036. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  77037. }
  77038. if (this._ranges) {
  77039. result._ranges = {};
  77040. for (var rangeName in this._ranges) {
  77041. var range = this._ranges[rangeName];
  77042. if (range) {
  77043. result._ranges[rangeName] = range.clone();
  77044. }
  77045. }
  77046. }
  77047. this._isDirty = true;
  77048. return result;
  77049. };
  77050. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  77051. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  77052. this.bones.forEach(function (bone) {
  77053. bone.animations.forEach(function (animation) {
  77054. animation.enableBlending = true;
  77055. animation.blendingSpeed = blendingSpeed;
  77056. });
  77057. });
  77058. };
  77059. Skeleton.prototype.dispose = function () {
  77060. this._meshesWithPoseMatrix = [];
  77061. // Animations
  77062. this.getScene().stopAnimation(this);
  77063. // Remove from scene
  77064. this.getScene().removeSkeleton(this);
  77065. };
  77066. Skeleton.prototype.serialize = function () {
  77067. var serializationObject = {};
  77068. serializationObject.name = this.name;
  77069. serializationObject.id = this.id;
  77070. if (this.dimensionsAtRest) {
  77071. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  77072. }
  77073. serializationObject.bones = [];
  77074. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77075. for (var index = 0; index < this.bones.length; index++) {
  77076. var bone = this.bones[index];
  77077. var parent_2 = bone.getParent();
  77078. var serializedBone = {
  77079. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  77080. name: bone.name,
  77081. matrix: bone.getBaseMatrix().toArray(),
  77082. rest: bone.getRestPose().toArray()
  77083. };
  77084. serializationObject.bones.push(serializedBone);
  77085. if (bone.length) {
  77086. serializedBone.length = bone.length;
  77087. }
  77088. if (bone.animations && bone.animations.length > 0) {
  77089. serializedBone.animation = bone.animations[0].serialize();
  77090. }
  77091. serializationObject.ranges = [];
  77092. for (var name in this._ranges) {
  77093. var source = this._ranges[name];
  77094. if (!source) {
  77095. continue;
  77096. }
  77097. var range = {};
  77098. range.name = name;
  77099. range.from = source.from;
  77100. range.to = source.to;
  77101. serializationObject.ranges.push(range);
  77102. }
  77103. }
  77104. return serializationObject;
  77105. };
  77106. Skeleton.Parse = function (parsedSkeleton, scene) {
  77107. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77108. if (parsedSkeleton.dimensionsAtRest) {
  77109. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77110. }
  77111. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77112. var index;
  77113. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77114. var parsedBone = parsedSkeleton.bones[index];
  77115. var parentBone = null;
  77116. if (parsedBone.parentBoneIndex > -1) {
  77117. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77118. }
  77119. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77120. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77121. if (parsedBone.length) {
  77122. bone.length = parsedBone.length;
  77123. }
  77124. if (parsedBone.animation) {
  77125. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77126. }
  77127. }
  77128. // placed after bones, so createAnimationRange can cascade down
  77129. if (parsedSkeleton.ranges) {
  77130. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77131. var data = parsedSkeleton.ranges[index];
  77132. skeleton.createAnimationRange(data.name, data.from, data.to);
  77133. }
  77134. }
  77135. return skeleton;
  77136. };
  77137. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77138. if (forceUpdate === void 0) { forceUpdate = false; }
  77139. var renderId = this._scene.getRenderId();
  77140. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77141. this.bones[0].computeAbsoluteTransforms();
  77142. this._lastAbsoluteTransformsUpdateId = renderId;
  77143. }
  77144. };
  77145. Skeleton.prototype.getPoseMatrix = function () {
  77146. var poseMatrix = null;
  77147. if (this._meshesWithPoseMatrix.length > 0) {
  77148. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77149. }
  77150. return poseMatrix;
  77151. };
  77152. Skeleton.prototype.sortBones = function () {
  77153. var bones = new Array();
  77154. var visited = new Array(this.bones.length);
  77155. for (var index = 0; index < this.bones.length; index++) {
  77156. this._sortBones(index, bones, visited);
  77157. }
  77158. this.bones = bones;
  77159. };
  77160. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77161. if (visited[index]) {
  77162. return;
  77163. }
  77164. visited[index] = true;
  77165. var bone = this.bones[index];
  77166. if (bone._index === undefined) {
  77167. bone._index = index;
  77168. }
  77169. var parentBone = bone.getParent();
  77170. if (parentBone) {
  77171. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77172. }
  77173. bones.push(bone);
  77174. };
  77175. return Skeleton;
  77176. }());
  77177. BABYLON.Skeleton = Skeleton;
  77178. })(BABYLON || (BABYLON = {}));
  77179. //# sourceMappingURL=babylon.skeleton.js.map
  77180. "use strict";
  77181. var BABYLON;
  77182. (function (BABYLON) {
  77183. var SphericalPolynomial = /** @class */ (function () {
  77184. function SphericalPolynomial() {
  77185. this.x = BABYLON.Vector3.Zero();
  77186. this.y = BABYLON.Vector3.Zero();
  77187. this.z = BABYLON.Vector3.Zero();
  77188. this.xx = BABYLON.Vector3.Zero();
  77189. this.yy = BABYLON.Vector3.Zero();
  77190. this.zz = BABYLON.Vector3.Zero();
  77191. this.xy = BABYLON.Vector3.Zero();
  77192. this.yz = BABYLON.Vector3.Zero();
  77193. this.zx = BABYLON.Vector3.Zero();
  77194. }
  77195. SphericalPolynomial.prototype.addAmbient = function (color) {
  77196. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77197. this.xx = this.xx.add(colorVector);
  77198. this.yy = this.yy.add(colorVector);
  77199. this.zz = this.zz.add(colorVector);
  77200. };
  77201. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77202. var result = new SphericalPolynomial();
  77203. result.x = harmonics.L11.scale(1.02333);
  77204. result.y = harmonics.L1_1.scale(1.02333);
  77205. result.z = harmonics.L10.scale(1.02333);
  77206. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77207. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77208. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77209. result.yz = harmonics.L2_1.scale(0.858086);
  77210. result.zx = harmonics.L21.scale(0.858086);
  77211. result.xy = harmonics.L2_2.scale(0.858086);
  77212. result.scale(1.0 / Math.PI);
  77213. return result;
  77214. };
  77215. SphericalPolynomial.prototype.scale = function (scale) {
  77216. this.x = this.x.scale(scale);
  77217. this.y = this.y.scale(scale);
  77218. this.z = this.z.scale(scale);
  77219. this.xx = this.xx.scale(scale);
  77220. this.yy = this.yy.scale(scale);
  77221. this.zz = this.zz.scale(scale);
  77222. this.yz = this.yz.scale(scale);
  77223. this.zx = this.zx.scale(scale);
  77224. this.xy = this.xy.scale(scale);
  77225. };
  77226. return SphericalPolynomial;
  77227. }());
  77228. BABYLON.SphericalPolynomial = SphericalPolynomial;
  77229. var SphericalHarmonics = /** @class */ (function () {
  77230. function SphericalHarmonics() {
  77231. this.L00 = BABYLON.Vector3.Zero();
  77232. this.L1_1 = BABYLON.Vector3.Zero();
  77233. this.L10 = BABYLON.Vector3.Zero();
  77234. this.L11 = BABYLON.Vector3.Zero();
  77235. this.L2_2 = BABYLON.Vector3.Zero();
  77236. this.L2_1 = BABYLON.Vector3.Zero();
  77237. this.L20 = BABYLON.Vector3.Zero();
  77238. this.L21 = BABYLON.Vector3.Zero();
  77239. this.L22 = BABYLON.Vector3.Zero();
  77240. }
  77241. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  77242. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77243. var c = colorVector.scale(deltaSolidAngle);
  77244. this.L00 = this.L00.add(c.scale(0.282095));
  77245. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  77246. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  77247. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  77248. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  77249. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  77250. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  77251. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  77252. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  77253. };
  77254. SphericalHarmonics.prototype.scale = function (scale) {
  77255. this.L00 = this.L00.scale(scale);
  77256. this.L1_1 = this.L1_1.scale(scale);
  77257. this.L10 = this.L10.scale(scale);
  77258. this.L11 = this.L11.scale(scale);
  77259. this.L2_2 = this.L2_2.scale(scale);
  77260. this.L2_1 = this.L2_1.scale(scale);
  77261. this.L20 = this.L20.scale(scale);
  77262. this.L21 = this.L21.scale(scale);
  77263. this.L22 = this.L22.scale(scale);
  77264. };
  77265. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  77266. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  77267. //
  77268. // E_lm = A_l * L_lm
  77269. //
  77270. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  77271. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  77272. // the scaling factors are given in equation 9.
  77273. // Constant (Band 0)
  77274. this.L00 = this.L00.scale(3.141593);
  77275. // Linear (Band 1)
  77276. this.L1_1 = this.L1_1.scale(2.094395);
  77277. this.L10 = this.L10.scale(2.094395);
  77278. this.L11 = this.L11.scale(2.094395);
  77279. // Quadratic (Band 2)
  77280. this.L2_2 = this.L2_2.scale(0.785398);
  77281. this.L2_1 = this.L2_1.scale(0.785398);
  77282. this.L20 = this.L20.scale(0.785398);
  77283. this.L21 = this.L21.scale(0.785398);
  77284. this.L22 = this.L22.scale(0.785398);
  77285. };
  77286. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  77287. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  77288. // L = (1/pi) * E * rho
  77289. //
  77290. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  77291. this.scale(1.0 / Math.PI);
  77292. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  77293. // (The pixel shader must apply albedo after texture fetches, etc).
  77294. };
  77295. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  77296. var result = new SphericalHarmonics();
  77297. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  77298. result.L1_1 = polynomial.y.scale(0.977204);
  77299. result.L10 = polynomial.z.scale(0.977204);
  77300. result.L11 = polynomial.x.scale(0.977204);
  77301. result.L2_2 = polynomial.xy.scale(1.16538);
  77302. result.L2_1 = polynomial.yz.scale(1.16538);
  77303. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  77304. result.L21 = polynomial.zx.scale(1.16538);
  77305. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  77306. result.scale(Math.PI);
  77307. return result;
  77308. };
  77309. return SphericalHarmonics;
  77310. }());
  77311. BABYLON.SphericalHarmonics = SphericalHarmonics;
  77312. })(BABYLON || (BABYLON = {}));
  77313. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  77314. "use strict";
  77315. var BABYLON;
  77316. (function (BABYLON) {
  77317. var FileFaceOrientation = /** @class */ (function () {
  77318. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  77319. this.name = name;
  77320. this.worldAxisForNormal = worldAxisForNormal;
  77321. this.worldAxisForFileX = worldAxisForFileX;
  77322. this.worldAxisForFileY = worldAxisForFileY;
  77323. }
  77324. return FileFaceOrientation;
  77325. }());
  77326. ;
  77327. /**
  77328. * Helper class dealing with the extraction of spherical polynomial dataArray
  77329. * from a cube map.
  77330. */
  77331. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  77332. function CubeMapToSphericalPolynomialTools() {
  77333. }
  77334. /**
  77335. * Converts a texture to the according Spherical Polynomial data.
  77336. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77337. *
  77338. * @param texture The texture to extract the information from.
  77339. * @return The Spherical Polynomial data.
  77340. */
  77341. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  77342. if (!texture.isCube) {
  77343. // Only supports cube Textures currently.
  77344. return null;
  77345. }
  77346. var size = texture.getSize().width;
  77347. var right = texture.readPixels(0);
  77348. var left = texture.readPixels(1);
  77349. var up;
  77350. var down;
  77351. if (texture.isRenderTarget) {
  77352. up = texture.readPixels(3);
  77353. down = texture.readPixels(2);
  77354. }
  77355. else {
  77356. up = texture.readPixels(2);
  77357. down = texture.readPixels(3);
  77358. }
  77359. var front = texture.readPixels(4);
  77360. var back = texture.readPixels(5);
  77361. var gammaSpace = texture.gammaSpace;
  77362. // Always read as RGBA.
  77363. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  77364. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77365. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77366. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77367. }
  77368. var cubeInfo = {
  77369. size: size,
  77370. right: right,
  77371. left: left,
  77372. up: up,
  77373. down: down,
  77374. front: front,
  77375. back: back,
  77376. format: format,
  77377. type: type,
  77378. gammaSpace: gammaSpace,
  77379. };
  77380. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  77381. };
  77382. /**
  77383. * Converts a cubemap to the according Spherical Polynomial data.
  77384. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77385. *
  77386. * @param cubeInfo The Cube map to extract the information from.
  77387. * @return The Spherical Polynomial data.
  77388. */
  77389. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  77390. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  77391. var totalSolidAngle = 0.0;
  77392. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  77393. var du = 2.0 / cubeInfo.size;
  77394. var dv = du;
  77395. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  77396. var minUV = du * 0.5 - 1.0;
  77397. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77398. var fileFace = this.FileFaces[faceIndex];
  77399. var dataArray = cubeInfo[fileFace.name];
  77400. var v = minUV;
  77401. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  77402. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  77403. // Because SP is still linear, so summation is fine in that basis.
  77404. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  77405. for (var y = 0; y < cubeInfo.size; y++) {
  77406. var u = minUV;
  77407. for (var x = 0; x < cubeInfo.size; x++) {
  77408. // World direction (not normalised)
  77409. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  77410. worldDirection.normalize();
  77411. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  77412. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  77413. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  77414. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  77415. // Handle Integer types.
  77416. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77417. r /= 255;
  77418. g /= 255;
  77419. b /= 255;
  77420. }
  77421. // Handle Gamma space textures.
  77422. if (cubeInfo.gammaSpace) {
  77423. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  77424. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  77425. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  77426. }
  77427. var color = new BABYLON.Color3(r, g, b);
  77428. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  77429. totalSolidAngle += deltaSolidAngle;
  77430. u += du;
  77431. }
  77432. v += dv;
  77433. }
  77434. }
  77435. // Solid angle for entire sphere is 4*pi
  77436. var sphereSolidAngle = 4.0 * Math.PI;
  77437. // Adjust the solid angle to allow for how many faces we processed.
  77438. var facesProcessed = 6.0;
  77439. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  77440. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  77441. // This is needed because the numerical integration over the cube uses a
  77442. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  77443. // and also to compensate for accumulative error due to float precision in the summation.
  77444. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  77445. sphericalHarmonics.scale(correctionFactor);
  77446. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  77447. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  77448. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  77449. };
  77450. CubeMapToSphericalPolynomialTools.FileFaces = [
  77451. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  77452. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  77453. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  77454. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  77455. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  77456. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  77457. ];
  77458. return CubeMapToSphericalPolynomialTools;
  77459. }());
  77460. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  77461. })(BABYLON || (BABYLON = {}));
  77462. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  77463. "use strict";
  77464. var BABYLON;
  77465. (function (BABYLON) {
  77466. /**
  77467. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  77468. */
  77469. var PanoramaToCubeMapTools = /** @class */ (function () {
  77470. function PanoramaToCubeMapTools() {
  77471. }
  77472. /**
  77473. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  77474. *
  77475. * @param float32Array The source data.
  77476. * @param inputWidth The width of the input panorama.
  77477. * @param inputhHeight The height of the input panorama.
  77478. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  77479. * @return The cubemap data
  77480. */
  77481. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  77482. if (!float32Array) {
  77483. throw "ConvertPanoramaToCubemap: input cannot be null";
  77484. }
  77485. if (float32Array.length != inputWidth * inputHeight * 3) {
  77486. throw "ConvertPanoramaToCubemap: input size is wrong";
  77487. }
  77488. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  77489. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  77490. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  77491. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  77492. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  77493. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  77494. return {
  77495. front: textureFront,
  77496. back: textureBack,
  77497. left: textureLeft,
  77498. right: textureRight,
  77499. up: textureUp,
  77500. down: textureDown,
  77501. size: size,
  77502. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  77503. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  77504. gammaSpace: false,
  77505. };
  77506. };
  77507. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  77508. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  77509. var textureArray = new Float32Array(buffer);
  77510. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  77511. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  77512. var dy = 1 / texSize;
  77513. var fy = 0;
  77514. for (var y = 0; y < texSize; y++) {
  77515. var xv1 = faceData[0];
  77516. var xv2 = faceData[2];
  77517. for (var x = 0; x < texSize; x++) {
  77518. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  77519. v.normalize();
  77520. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  77521. // 3 channels per pixels
  77522. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  77523. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  77524. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  77525. xv1 = xv1.add(rotDX1);
  77526. xv2 = xv2.add(rotDX2);
  77527. }
  77528. fy += dy;
  77529. }
  77530. return textureArray;
  77531. };
  77532. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  77533. var theta = Math.atan2(vDir.z, vDir.x);
  77534. var phi = Math.acos(vDir.y);
  77535. while (theta < -Math.PI)
  77536. theta += 2 * Math.PI;
  77537. while (theta > Math.PI)
  77538. theta -= 2 * Math.PI;
  77539. var dx = theta / Math.PI;
  77540. var dy = phi / Math.PI;
  77541. // recenter.
  77542. dx = dx * 0.5 + 0.5;
  77543. var px = Math.round(dx * inputWidth);
  77544. if (px < 0)
  77545. px = 0;
  77546. else if (px >= inputWidth)
  77547. px = inputWidth - 1;
  77548. var py = Math.round(dy * inputHeight);
  77549. if (py < 0)
  77550. py = 0;
  77551. else if (py >= inputHeight)
  77552. py = inputHeight - 1;
  77553. var inputY = (inputHeight - py - 1);
  77554. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  77555. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  77556. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  77557. return {
  77558. r: r,
  77559. g: g,
  77560. b: b
  77561. };
  77562. };
  77563. PanoramaToCubeMapTools.FACE_FRONT = [
  77564. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77565. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77566. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77567. new BABYLON.Vector3(1.0, 1.0, -1.0)
  77568. ];
  77569. PanoramaToCubeMapTools.FACE_BACK = [
  77570. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77571. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77572. new BABYLON.Vector3(1.0, 1.0, 1.0),
  77573. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  77574. ];
  77575. PanoramaToCubeMapTools.FACE_RIGHT = [
  77576. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77577. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77578. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77579. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77580. ];
  77581. PanoramaToCubeMapTools.FACE_LEFT = [
  77582. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77583. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77584. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77585. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  77586. ];
  77587. PanoramaToCubeMapTools.FACE_DOWN = [
  77588. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77589. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77590. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77591. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77592. ];
  77593. PanoramaToCubeMapTools.FACE_UP = [
  77594. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77595. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77596. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77597. new BABYLON.Vector3(1.0, -1.0, -1.0)
  77598. ];
  77599. return PanoramaToCubeMapTools;
  77600. }());
  77601. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  77602. })(BABYLON || (BABYLON = {}));
  77603. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  77604. "use strict";
  77605. var BABYLON;
  77606. (function (BABYLON) {
  77607. ;
  77608. /**
  77609. * This groups tools to convert HDR texture to native colors array.
  77610. */
  77611. var HDRTools = /** @class */ (function () {
  77612. function HDRTools() {
  77613. }
  77614. HDRTools.Ldexp = function (mantissa, exponent) {
  77615. if (exponent > 1023) {
  77616. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  77617. }
  77618. if (exponent < -1074) {
  77619. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  77620. }
  77621. return mantissa * Math.pow(2, exponent);
  77622. };
  77623. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  77624. if (exponent > 0) {
  77625. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  77626. float32array[index + 0] = red * exponent;
  77627. float32array[index + 1] = green * exponent;
  77628. float32array[index + 2] = blue * exponent;
  77629. }
  77630. else {
  77631. float32array[index + 0] = 0;
  77632. float32array[index + 1] = 0;
  77633. float32array[index + 2] = 0;
  77634. }
  77635. };
  77636. HDRTools.readStringLine = function (uint8array, startIndex) {
  77637. var line = "";
  77638. var character = "";
  77639. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  77640. character = String.fromCharCode(uint8array[i]);
  77641. if (character == "\n") {
  77642. break;
  77643. }
  77644. line += character;
  77645. }
  77646. return line;
  77647. };
  77648. /**
  77649. * Reads header information from an RGBE texture stored in a native array.
  77650. * More information on this format are available here:
  77651. * https://en.wikipedia.org/wiki/RGBE_image_format
  77652. *
  77653. * @param uint8array The binary file stored in native array.
  77654. * @return The header information.
  77655. */
  77656. HDRTools.RGBE_ReadHeader = function (uint8array) {
  77657. var height = 0;
  77658. var width = 0;
  77659. var line = this.readStringLine(uint8array, 0);
  77660. if (line[0] != '#' || line[1] != '?') {
  77661. throw "Bad HDR Format.";
  77662. }
  77663. var endOfHeader = false;
  77664. var findFormat = false;
  77665. var lineIndex = 0;
  77666. do {
  77667. lineIndex += (line.length + 1);
  77668. line = this.readStringLine(uint8array, lineIndex);
  77669. if (line == "FORMAT=32-bit_rle_rgbe") {
  77670. findFormat = true;
  77671. }
  77672. else if (line.length == 0) {
  77673. endOfHeader = true;
  77674. }
  77675. } while (!endOfHeader);
  77676. if (!findFormat) {
  77677. throw "HDR Bad header format, unsupported FORMAT";
  77678. }
  77679. lineIndex += (line.length + 1);
  77680. line = this.readStringLine(uint8array, lineIndex);
  77681. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  77682. var match = sizeRegexp.exec(line);
  77683. // TODO. Support +Y and -X if needed.
  77684. if (!match || match.length < 3) {
  77685. throw "HDR Bad header format, no size";
  77686. }
  77687. width = parseInt(match[2]);
  77688. height = parseInt(match[1]);
  77689. if (width < 8 || width > 0x7fff) {
  77690. throw "HDR Bad header format, unsupported size";
  77691. }
  77692. lineIndex += (line.length + 1);
  77693. return {
  77694. height: height,
  77695. width: width,
  77696. dataPosition: lineIndex
  77697. };
  77698. };
  77699. /**
  77700. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  77701. * This RGBE texture needs to store the information as a panorama.
  77702. *
  77703. * More information on this format are available here:
  77704. * https://en.wikipedia.org/wiki/RGBE_image_format
  77705. *
  77706. * @param buffer The binary file stored in an array buffer.
  77707. * @param size The expected size of the extracted cubemap.
  77708. * @return The Cube Map information.
  77709. */
  77710. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  77711. var uint8array = new Uint8Array(buffer);
  77712. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  77713. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  77714. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  77715. return cubeMapData;
  77716. };
  77717. /**
  77718. * Returns the pixels data extracted from an RGBE texture.
  77719. * This pixels will be stored left to right up to down in the R G B order in one array.
  77720. *
  77721. * More information on this format are available here:
  77722. * https://en.wikipedia.org/wiki/RGBE_image_format
  77723. *
  77724. * @param uint8array The binary file stored in an array buffer.
  77725. * @param hdrInfo The header information of the file.
  77726. * @return The pixels data in RGB right to left up to down order.
  77727. */
  77728. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  77729. // Keep for multi format supports.
  77730. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  77731. };
  77732. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  77733. var num_scanlines = hdrInfo.height;
  77734. var scanline_width = hdrInfo.width;
  77735. var a, b, c, d, count;
  77736. var dataIndex = hdrInfo.dataPosition;
  77737. var index = 0, endIndex = 0, i = 0;
  77738. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  77739. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  77740. // 3 channels of 4 bytes per pixel in float.
  77741. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  77742. var resultArray = new Float32Array(resultBuffer);
  77743. // read in each successive scanline
  77744. while (num_scanlines > 0) {
  77745. a = uint8array[dataIndex++];
  77746. b = uint8array[dataIndex++];
  77747. c = uint8array[dataIndex++];
  77748. d = uint8array[dataIndex++];
  77749. if (a != 2 || b != 2 || (c & 0x80)) {
  77750. // this file is not run length encoded
  77751. throw "HDR Bad header format, not RLE";
  77752. }
  77753. if (((c << 8) | d) != scanline_width) {
  77754. throw "HDR Bad header format, wrong scan line width";
  77755. }
  77756. index = 0;
  77757. // read each of the four channels for the scanline into the buffer
  77758. for (i = 0; i < 4; i++) {
  77759. endIndex = (i + 1) * scanline_width;
  77760. while (index < endIndex) {
  77761. a = uint8array[dataIndex++];
  77762. b = uint8array[dataIndex++];
  77763. if (a > 128) {
  77764. // a run of the same value
  77765. count = a - 128;
  77766. if ((count == 0) || (count > endIndex - index)) {
  77767. throw "HDR Bad Format, bad scanline data (run)";
  77768. }
  77769. while (count-- > 0) {
  77770. scanLineArray[index++] = b;
  77771. }
  77772. }
  77773. else {
  77774. // a non-run
  77775. count = a;
  77776. if ((count == 0) || (count > endIndex - index)) {
  77777. throw "HDR Bad Format, bad scanline data (non-run)";
  77778. }
  77779. scanLineArray[index++] = b;
  77780. if (--count > 0) {
  77781. for (var j = 0; j < count; j++) {
  77782. scanLineArray[index++] = uint8array[dataIndex++];
  77783. }
  77784. }
  77785. }
  77786. }
  77787. }
  77788. // now convert data from buffer into floats
  77789. for (i = 0; i < scanline_width; i++) {
  77790. a = scanLineArray[i];
  77791. b = scanLineArray[i + scanline_width];
  77792. c = scanLineArray[i + 2 * scanline_width];
  77793. d = scanLineArray[i + 3 * scanline_width];
  77794. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  77795. }
  77796. num_scanlines--;
  77797. }
  77798. return resultArray;
  77799. };
  77800. return HDRTools;
  77801. }());
  77802. BABYLON.HDRTools = HDRTools;
  77803. })(BABYLON || (BABYLON = {}));
  77804. //# sourceMappingURL=babylon.hdr.js.map
  77805. "use strict";
  77806. var BABYLON;
  77807. (function (BABYLON) {
  77808. /**
  77809. * This represents a texture coming from an HDR input.
  77810. *
  77811. * The only supported format is currently panorama picture stored in RGBE format.
  77812. * Example of such files can be found on HDRLib: http://hdrlib.com/
  77813. */
  77814. var HDRCubeTexture = /** @class */ (function (_super) {
  77815. __extends(HDRCubeTexture, _super);
  77816. /**
  77817. * Instantiates an HDRTexture from the following parameters.
  77818. *
  77819. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  77820. * @param scene The scene the texture will be used in
  77821. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  77822. * @param noMipmap Forces to not generate the mipmap if true
  77823. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  77824. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  77825. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  77826. */
  77827. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  77828. if (noMipmap === void 0) { noMipmap = false; }
  77829. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77830. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77831. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77832. if (onLoad === void 0) { onLoad = null; }
  77833. if (onError === void 0) { onError = null; }
  77834. var _this = _super.call(this, scene) || this;
  77835. _this._useInGammaSpace = false;
  77836. _this._generateHarmonics = true;
  77837. _this._isBABYLONPreprocessed = false;
  77838. _this._onLoad = null;
  77839. _this._onError = null;
  77840. /**
  77841. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  77842. */
  77843. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  77844. /**
  77845. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  77846. * This is usefull at run time to apply the good shader.
  77847. */
  77848. _this.isPMREM = false;
  77849. _this._isBlocking = true;
  77850. /**
  77851. * Gets or sets the center of the bounding box associated with the cube texture
  77852. * It must define where the camera used to render the texture was set
  77853. */
  77854. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  77855. if (!url) {
  77856. return _this;
  77857. }
  77858. _this.name = url;
  77859. _this.url = url;
  77860. _this.hasAlpha = false;
  77861. _this.isCube = true;
  77862. _this._textureMatrix = BABYLON.Matrix.Identity();
  77863. _this._onLoad = onLoad;
  77864. _this._onError = onError;
  77865. _this.gammaSpace = false;
  77866. var caps = scene.getEngine().getCaps();
  77867. if (size) {
  77868. _this._isBABYLONPreprocessed = false;
  77869. _this._noMipmap = noMipmap;
  77870. _this._size = size;
  77871. _this._useInGammaSpace = useInGammaSpace;
  77872. _this._usePMREMGenerator = usePMREMGenerator &&
  77873. caps.textureLOD &&
  77874. caps.textureFloat &&
  77875. !_this._useInGammaSpace;
  77876. }
  77877. else {
  77878. _this._isBABYLONPreprocessed = true;
  77879. _this._noMipmap = false;
  77880. _this._useInGammaSpace = false;
  77881. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  77882. !_this._useInGammaSpace;
  77883. }
  77884. _this.isPMREM = _this._usePMREMGenerator;
  77885. _this._texture = _this._getFromCache(url, _this._noMipmap);
  77886. if (!_this._texture) {
  77887. if (!scene.useDelayedTextureLoading) {
  77888. _this.loadTexture();
  77889. }
  77890. else {
  77891. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77892. }
  77893. }
  77894. return _this;
  77895. }
  77896. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  77897. /**
  77898. * Gets wether or not the texture is blocking during loading.
  77899. */
  77900. get: function () {
  77901. return this._isBlocking;
  77902. },
  77903. /**
  77904. * Sets wether or not the texture is blocking during loading.
  77905. */
  77906. set: function (value) {
  77907. this._isBlocking = value;
  77908. },
  77909. enumerable: true,
  77910. configurable: true
  77911. });
  77912. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  77913. get: function () {
  77914. return this._boundingBoxSize;
  77915. },
  77916. /**
  77917. * Gets or sets the size of the bounding box associated with the cube texture
  77918. * When defined, the cubemap will switch to local mode
  77919. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  77920. * @example https://www.babylonjs-playground.com/#RNASML
  77921. */
  77922. set: function (value) {
  77923. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  77924. return;
  77925. }
  77926. this._boundingBoxSize = value;
  77927. var scene = this.getScene();
  77928. if (scene) {
  77929. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  77930. }
  77931. },
  77932. enumerable: true,
  77933. configurable: true
  77934. });
  77935. /**
  77936. * Occurs when the file is a preprocessed .babylon.hdr file.
  77937. */
  77938. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  77939. var _this = this;
  77940. var mipLevels = 0;
  77941. var floatArrayView = null;
  77942. var scene = this.getScene();
  77943. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  77944. var mips = new Array();
  77945. if (!floatArrayView) {
  77946. return mips;
  77947. }
  77948. var startIndex = 30;
  77949. for (var level = 0; level < mipLevels; level++) {
  77950. mips.push([]);
  77951. // Fill each pixel of the mip level.
  77952. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  77953. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77954. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  77955. mips[level].push(faceData);
  77956. startIndex += faceSize;
  77957. }
  77958. }
  77959. return mips;
  77960. } : null;
  77961. var callback = function (buffer) {
  77962. var scene = _this.getScene();
  77963. if (!scene) {
  77964. return null;
  77965. }
  77966. // Create Native Array Views
  77967. var intArrayView = new Int32Array(buffer);
  77968. floatArrayView = new Float32Array(buffer);
  77969. // Fill header.
  77970. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  77971. _this._size = intArrayView[1]; // CubeMap max mip face size.
  77972. // Update Texture Information.
  77973. if (!_this._texture) {
  77974. return null;
  77975. }
  77976. _this._texture.updateSize(_this._size, _this._size);
  77977. // Fill polynomial information.
  77978. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  77979. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  77980. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  77981. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  77982. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  77983. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  77984. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  77985. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  77986. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  77987. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  77988. _this.sphericalPolynomial = sphericalPolynomial;
  77989. // Fill pixel data.
  77990. mipLevels = intArrayView[29]; // Number of mip levels.
  77991. var startIndex = 30;
  77992. var data = [];
  77993. var faceSize = Math.pow(_this._size, 2) * 3;
  77994. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77995. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  77996. startIndex += faceSize;
  77997. }
  77998. var results = [];
  77999. var byteArray = null;
  78000. // Push each faces.
  78001. for (var k = 0; k < 6; k++) {
  78002. var dataFace = null;
  78003. // To be deprecated.
  78004. if (version === 1) {
  78005. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  78006. dataFace = data[j];
  78007. }
  78008. // If special cases.
  78009. if (!mipmapGenerator && dataFace) {
  78010. if (!scene.getEngine().getCaps().textureFloat) {
  78011. // 3 channels of 1 bytes per pixel in bytes.
  78012. var byteBuffer = new ArrayBuffer(faceSize);
  78013. byteArray = new Uint8Array(byteBuffer);
  78014. }
  78015. for (var i = 0; i < _this._size * _this._size; i++) {
  78016. // Put in gamma space if requested.
  78017. if (_this._useInGammaSpace) {
  78018. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78019. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78020. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78021. }
  78022. // Convert to int texture for fallback.
  78023. if (byteArray) {
  78024. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78025. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78026. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78027. // May use luminance instead if the result is not accurate.
  78028. var max = Math.max(Math.max(r, g), b);
  78029. if (max > 255) {
  78030. var scale = 255 / max;
  78031. r *= scale;
  78032. g *= scale;
  78033. b *= scale;
  78034. }
  78035. byteArray[(i * 3) + 0] = r;
  78036. byteArray[(i * 3) + 1] = g;
  78037. byteArray[(i * 3) + 2] = b;
  78038. }
  78039. }
  78040. }
  78041. // Fill the array accordingly.
  78042. if (byteArray) {
  78043. results.push(byteArray);
  78044. }
  78045. else {
  78046. results.push(dataFace);
  78047. }
  78048. }
  78049. return results;
  78050. };
  78051. if (scene) {
  78052. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  78053. }
  78054. };
  78055. /**
  78056. * Occurs when the file is raw .hdr file.
  78057. */
  78058. HDRCubeTexture.prototype.loadHDRTexture = function () {
  78059. var _this = this;
  78060. var callback = function (buffer) {
  78061. var scene = _this.getScene();
  78062. if (!scene) {
  78063. return null;
  78064. }
  78065. // Extract the raw linear data.
  78066. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  78067. // Generate harmonics if needed.
  78068. if (_this._generateHarmonics) {
  78069. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  78070. _this.sphericalPolynomial = sphericalPolynomial;
  78071. }
  78072. var results = [];
  78073. var byteArray = null;
  78074. // Push each faces.
  78075. for (var j = 0; j < 6; j++) {
  78076. // Create uintarray fallback.
  78077. if (!scene.getEngine().getCaps().textureFloat) {
  78078. // 3 channels of 1 bytes per pixel in bytes.
  78079. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  78080. byteArray = new Uint8Array(byteBuffer);
  78081. }
  78082. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  78083. // If special cases.
  78084. if (_this._useInGammaSpace || byteArray) {
  78085. for (var i = 0; i < _this._size * _this._size; i++) {
  78086. // Put in gamma space if requested.
  78087. if (_this._useInGammaSpace) {
  78088. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78089. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78090. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78091. }
  78092. // Convert to int texture for fallback.
  78093. if (byteArray) {
  78094. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78095. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78096. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78097. // May use luminance instead if the result is not accurate.
  78098. var max = Math.max(Math.max(r, g), b);
  78099. if (max > 255) {
  78100. var scale = 255 / max;
  78101. r *= scale;
  78102. g *= scale;
  78103. b *= scale;
  78104. }
  78105. byteArray[(i * 3) + 0] = r;
  78106. byteArray[(i * 3) + 1] = g;
  78107. byteArray[(i * 3) + 2] = b;
  78108. }
  78109. }
  78110. }
  78111. if (byteArray) {
  78112. results.push(byteArray);
  78113. }
  78114. else {
  78115. results.push(dataFace);
  78116. }
  78117. }
  78118. return results;
  78119. };
  78120. var mipmapGenerator = null;
  78121. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78122. // if (!this._noMipmap &&
  78123. // this._usePMREMGenerator) {
  78124. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78125. // // Custom setup of the generator matching with the PBR shader values.
  78126. // var generator = new BABYLON.PMREMGenerator(data,
  78127. // this._size,
  78128. // this._size,
  78129. // 0,
  78130. // 3,
  78131. // this.getScene().getEngine().getCaps().textureFloat,
  78132. // 2048,
  78133. // 0.25,
  78134. // false,
  78135. // true);
  78136. // return generator.filterCubeMap();
  78137. // };
  78138. // }
  78139. var scene = this.getScene();
  78140. if (scene) {
  78141. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  78142. }
  78143. };
  78144. /**
  78145. * Starts the loading process of the texture.
  78146. */
  78147. HDRCubeTexture.prototype.loadTexture = function () {
  78148. if (this._isBABYLONPreprocessed) {
  78149. this.loadBabylonTexture();
  78150. }
  78151. else {
  78152. this.loadHDRTexture();
  78153. }
  78154. };
  78155. HDRCubeTexture.prototype.clone = function () {
  78156. var scene = this.getScene();
  78157. if (!scene) {
  78158. return this;
  78159. }
  78160. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78161. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78162. // Base texture
  78163. newTexture.level = this.level;
  78164. newTexture.wrapU = this.wrapU;
  78165. newTexture.wrapV = this.wrapV;
  78166. newTexture.coordinatesIndex = this.coordinatesIndex;
  78167. newTexture.coordinatesMode = this.coordinatesMode;
  78168. return newTexture;
  78169. };
  78170. // Methods
  78171. HDRCubeTexture.prototype.delayLoad = function () {
  78172. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78173. return;
  78174. }
  78175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78176. this._texture = this._getFromCache(this.url, this._noMipmap);
  78177. if (!this._texture) {
  78178. this.loadTexture();
  78179. }
  78180. };
  78181. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78182. return this._textureMatrix;
  78183. };
  78184. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78185. this._textureMatrix = value;
  78186. };
  78187. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78188. var texture = null;
  78189. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78190. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78191. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78192. texture.name = parsedTexture.name;
  78193. texture.hasAlpha = parsedTexture.hasAlpha;
  78194. texture.level = parsedTexture.level;
  78195. texture.coordinatesMode = parsedTexture.coordinatesMode;
  78196. texture.isBlocking = parsedTexture.isBlocking;
  78197. }
  78198. if (texture) {
  78199. if (parsedTexture.boundingBoxPosition) {
  78200. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  78201. }
  78202. if (parsedTexture.boundingBoxSize) {
  78203. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  78204. }
  78205. }
  78206. return texture;
  78207. };
  78208. HDRCubeTexture.prototype.serialize = function () {
  78209. if (!this.name) {
  78210. return null;
  78211. }
  78212. var serializationObject = {};
  78213. serializationObject.name = this.name;
  78214. serializationObject.hasAlpha = this.hasAlpha;
  78215. serializationObject.isCube = true;
  78216. serializationObject.level = this.level;
  78217. serializationObject.size = this._size;
  78218. serializationObject.coordinatesMode = this.coordinatesMode;
  78219. serializationObject.useInGammaSpace = this._useInGammaSpace;
  78220. serializationObject.generateHarmonics = this._generateHarmonics;
  78221. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  78222. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  78223. serializationObject.customType = "BABYLON.HDRCubeTexture";
  78224. serializationObject.noMipmap = this._noMipmap;
  78225. serializationObject.isBlocking = this._isBlocking;
  78226. return serializationObject;
  78227. };
  78228. /**
  78229. * Saves as a file the data contained in the texture in a binary format.
  78230. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78231. * as the spherical used in the lighting.
  78232. * @param url The HDR file url.
  78233. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78234. * @param onError Method called if any error happens during download.
  78235. * @return The packed binary data.
  78236. */
  78237. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  78238. if (onError === void 0) { onError = null; }
  78239. var callback = function (buffer) {
  78240. var data = new Blob([buffer], { type: 'application/octet-stream' });
  78241. // Returns a URL you can use as a href.
  78242. var objUrl = window.URL.createObjectURL(data);
  78243. // Simulates a link to it and click to dowload.
  78244. var a = document.createElement("a");
  78245. document.body.appendChild(a);
  78246. a.style.display = "none";
  78247. a.href = objUrl;
  78248. a.download = "envmap.babylon.hdr";
  78249. a.click();
  78250. };
  78251. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  78252. };
  78253. /**
  78254. * Serializes the data contained in the texture in a binary format.
  78255. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78256. * as the spherical used in the lighting.
  78257. * @param url The HDR file url.
  78258. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78259. * @param onError Method called if any error happens during download.
  78260. * @return The packed binary data.
  78261. */
  78262. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  78263. if (onError === void 0) { onError = null; }
  78264. // Needs the url tho create the texture.
  78265. if (!url) {
  78266. return;
  78267. }
  78268. // Check Power of two size.
  78269. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  78270. return;
  78271. }
  78272. // Coming Back in 3.x.
  78273. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  78274. };
  78275. HDRCubeTexture._facesMapping = [
  78276. "right",
  78277. "left",
  78278. "up",
  78279. "down",
  78280. "front",
  78281. "back"
  78282. ];
  78283. return HDRCubeTexture;
  78284. }(BABYLON.BaseTexture));
  78285. BABYLON.HDRCubeTexture = HDRCubeTexture;
  78286. })(BABYLON || (BABYLON = {}));
  78287. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  78288. "use strict";
  78289. var BABYLON;
  78290. (function (BABYLON) {
  78291. var IndexedVector2 = /** @class */ (function (_super) {
  78292. __extends(IndexedVector2, _super);
  78293. function IndexedVector2(original, index) {
  78294. var _this = _super.call(this, original.x, original.y) || this;
  78295. _this.index = index;
  78296. return _this;
  78297. }
  78298. return IndexedVector2;
  78299. }(BABYLON.Vector2));
  78300. var PolygonPoints = /** @class */ (function () {
  78301. function PolygonPoints() {
  78302. this.elements = new Array();
  78303. }
  78304. PolygonPoints.prototype.add = function (originalPoints) {
  78305. var _this = this;
  78306. var result = new Array();
  78307. originalPoints.forEach(function (point) {
  78308. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  78309. var newPoint = new IndexedVector2(point, _this.elements.length);
  78310. result.push(newPoint);
  78311. _this.elements.push(newPoint);
  78312. }
  78313. });
  78314. return result;
  78315. };
  78316. PolygonPoints.prototype.computeBounds = function () {
  78317. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78318. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78319. this.elements.forEach(function (point) {
  78320. // x
  78321. if (point.x < lmin.x) {
  78322. lmin.x = point.x;
  78323. }
  78324. else if (point.x > lmax.x) {
  78325. lmax.x = point.x;
  78326. }
  78327. // y
  78328. if (point.y < lmin.y) {
  78329. lmin.y = point.y;
  78330. }
  78331. else if (point.y > lmax.y) {
  78332. lmax.y = point.y;
  78333. }
  78334. });
  78335. return {
  78336. min: lmin,
  78337. max: lmax,
  78338. width: lmax.x - lmin.x,
  78339. height: lmax.y - lmin.y
  78340. };
  78341. };
  78342. return PolygonPoints;
  78343. }());
  78344. var Polygon = /** @class */ (function () {
  78345. function Polygon() {
  78346. }
  78347. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  78348. return [
  78349. new BABYLON.Vector2(xmin, ymin),
  78350. new BABYLON.Vector2(xmax, ymin),
  78351. new BABYLON.Vector2(xmax, ymax),
  78352. new BABYLON.Vector2(xmin, ymax)
  78353. ];
  78354. };
  78355. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  78356. if (cx === void 0) { cx = 0; }
  78357. if (cy === void 0) { cy = 0; }
  78358. if (numberOfSides === void 0) { numberOfSides = 32; }
  78359. var result = new Array();
  78360. var angle = 0;
  78361. var increment = (Math.PI * 2) / numberOfSides;
  78362. for (var i = 0; i < numberOfSides; i++) {
  78363. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  78364. angle -= increment;
  78365. }
  78366. return result;
  78367. };
  78368. Polygon.Parse = function (input) {
  78369. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  78370. var i, result = [];
  78371. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  78372. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  78373. }
  78374. return result;
  78375. };
  78376. Polygon.StartingAt = function (x, y) {
  78377. return BABYLON.Path2.StartingAt(x, y);
  78378. };
  78379. return Polygon;
  78380. }());
  78381. BABYLON.Polygon = Polygon;
  78382. var PolygonMeshBuilder = /** @class */ (function () {
  78383. function PolygonMeshBuilder(name, contours, scene) {
  78384. this._points = new PolygonPoints();
  78385. this._outlinepoints = new PolygonPoints();
  78386. this._holes = new Array();
  78387. this._epoints = new Array();
  78388. this._eholes = new Array();
  78389. this._name = name;
  78390. this._scene = scene;
  78391. var points;
  78392. if (contours instanceof BABYLON.Path2) {
  78393. points = contours.getPoints();
  78394. }
  78395. else {
  78396. points = contours;
  78397. }
  78398. this._addToepoint(points);
  78399. this._points.add(points);
  78400. this._outlinepoints.add(points);
  78401. if (typeof earcut === 'undefined') {
  78402. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  78403. }
  78404. }
  78405. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  78406. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  78407. var p = points_1[_i];
  78408. this._epoints.push(p.x, p.y);
  78409. }
  78410. };
  78411. PolygonMeshBuilder.prototype.addHole = function (hole) {
  78412. this._points.add(hole);
  78413. var holepoints = new PolygonPoints();
  78414. holepoints.add(hole);
  78415. this._holes.push(holepoints);
  78416. this._eholes.push(this._epoints.length / 2);
  78417. this._addToepoint(hole);
  78418. return this;
  78419. };
  78420. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  78421. var _this = this;
  78422. if (updatable === void 0) { updatable = false; }
  78423. if (depth === void 0) { depth = 0; }
  78424. var result = new BABYLON.Mesh(this._name, this._scene);
  78425. var normals = new Array();
  78426. var positions = new Array();
  78427. var uvs = new Array();
  78428. var bounds = this._points.computeBounds();
  78429. this._points.elements.forEach(function (p) {
  78430. normals.push(0, 1.0, 0);
  78431. positions.push(p.x, 0, p.y);
  78432. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  78433. });
  78434. var indices = new Array();
  78435. var res = earcut(this._epoints, this._eholes, 2);
  78436. for (var i = 0; i < res.length; i++) {
  78437. indices.push(res[i]);
  78438. }
  78439. if (depth > 0) {
  78440. var positionscount = (positions.length / 3); //get the current pointcount
  78441. this._points.elements.forEach(function (p) {
  78442. normals.push(0, -1.0, 0);
  78443. positions.push(p.x, -depth, p.y);
  78444. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  78445. });
  78446. var totalCount = indices.length;
  78447. for (var i = 0; i < totalCount; i += 3) {
  78448. var i0 = indices[i + 0];
  78449. var i1 = indices[i + 1];
  78450. var i2 = indices[i + 2];
  78451. indices.push(i2 + positionscount);
  78452. indices.push(i1 + positionscount);
  78453. indices.push(i0 + positionscount);
  78454. }
  78455. //Add the sides
  78456. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  78457. this._holes.forEach(function (hole) {
  78458. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  78459. });
  78460. }
  78461. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  78462. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  78463. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  78464. result.setIndices(indices);
  78465. return result;
  78466. };
  78467. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  78468. var StartIndex = positions.length / 3;
  78469. var ulength = 0;
  78470. for (var i = 0; i < points.elements.length; i++) {
  78471. var p = points.elements[i];
  78472. var p1;
  78473. if ((i + 1) > points.elements.length - 1) {
  78474. p1 = points.elements[0];
  78475. }
  78476. else {
  78477. p1 = points.elements[i + 1];
  78478. }
  78479. positions.push(p.x, 0, p.y);
  78480. positions.push(p.x, -depth, p.y);
  78481. positions.push(p1.x, 0, p1.y);
  78482. positions.push(p1.x, -depth, p1.y);
  78483. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  78484. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  78485. var v3 = v2.subtract(v1);
  78486. var v4 = new BABYLON.Vector3(0, 1, 0);
  78487. var vn = BABYLON.Vector3.Cross(v3, v4);
  78488. vn = vn.normalize();
  78489. uvs.push(ulength / bounds.width, 0);
  78490. uvs.push(ulength / bounds.width, 1);
  78491. ulength += v3.length();
  78492. uvs.push((ulength / bounds.width), 0);
  78493. uvs.push((ulength / bounds.width), 1);
  78494. if (!flip) {
  78495. normals.push(-vn.x, -vn.y, -vn.z);
  78496. normals.push(-vn.x, -vn.y, -vn.z);
  78497. normals.push(-vn.x, -vn.y, -vn.z);
  78498. normals.push(-vn.x, -vn.y, -vn.z);
  78499. indices.push(StartIndex);
  78500. indices.push(StartIndex + 1);
  78501. indices.push(StartIndex + 2);
  78502. indices.push(StartIndex + 1);
  78503. indices.push(StartIndex + 3);
  78504. indices.push(StartIndex + 2);
  78505. }
  78506. else {
  78507. normals.push(vn.x, vn.y, vn.z);
  78508. normals.push(vn.x, vn.y, vn.z);
  78509. normals.push(vn.x, vn.y, vn.z);
  78510. normals.push(vn.x, vn.y, vn.z);
  78511. indices.push(StartIndex);
  78512. indices.push(StartIndex + 2);
  78513. indices.push(StartIndex + 1);
  78514. indices.push(StartIndex + 1);
  78515. indices.push(StartIndex + 2);
  78516. indices.push(StartIndex + 3);
  78517. }
  78518. StartIndex += 4;
  78519. }
  78520. ;
  78521. };
  78522. return PolygonMeshBuilder;
  78523. }());
  78524. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  78525. })(BABYLON || (BABYLON = {}));
  78526. //# sourceMappingURL=babylon.polygonMesh.js.map
  78527. "use strict";
  78528. var BABYLON;
  78529. (function (BABYLON) {
  78530. // Unique ID when we import meshes from Babylon to CSG
  78531. var currentCSGMeshId = 0;
  78532. // # class Vertex
  78533. // Represents a vertex of a polygon. Use your own vertex class instead of this
  78534. // one to provide additional features like texture coordinates and vertex
  78535. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  78536. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  78537. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  78538. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  78539. // is not used anywhere else.
  78540. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  78541. var Vertex = /** @class */ (function () {
  78542. function Vertex(pos, normal, uv) {
  78543. this.pos = pos;
  78544. this.normal = normal;
  78545. this.uv = uv;
  78546. }
  78547. Vertex.prototype.clone = function () {
  78548. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  78549. };
  78550. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  78551. // orientation of a polygon is flipped.
  78552. Vertex.prototype.flip = function () {
  78553. this.normal = this.normal.scale(-1);
  78554. };
  78555. // Create a new vertex between this vertex and `other` by linearly
  78556. // interpolating all properties using a parameter of `t`. Subclasses should
  78557. // override this to interpolate additional properties.
  78558. Vertex.prototype.interpolate = function (other, t) {
  78559. 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));
  78560. };
  78561. return Vertex;
  78562. }());
  78563. // # class Plane
  78564. // Represents a plane in 3D space.
  78565. var Plane = /** @class */ (function () {
  78566. function Plane(normal, w) {
  78567. this.normal = normal;
  78568. this.w = w;
  78569. }
  78570. Plane.FromPoints = function (a, b, c) {
  78571. var v0 = c.subtract(a);
  78572. var v1 = b.subtract(a);
  78573. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  78574. return null;
  78575. }
  78576. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  78577. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  78578. };
  78579. Plane.prototype.clone = function () {
  78580. return new Plane(this.normal.clone(), this.w);
  78581. };
  78582. Plane.prototype.flip = function () {
  78583. this.normal.scaleInPlace(-1);
  78584. this.w = -this.w;
  78585. };
  78586. // Split `polygon` by this plane if needed, then put the polygon or polygon
  78587. // fragments in the appropriate lists. Coplanar polygons go into either
  78588. // `coplanarFront` or `coplanarBack` depending on their orientation with
  78589. // respect to this plane. Polygons in front or in back of this plane go into
  78590. // either `front` or `back`.
  78591. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  78592. var COPLANAR = 0;
  78593. var FRONT = 1;
  78594. var BACK = 2;
  78595. var SPANNING = 3;
  78596. // Classify each point as well as the entire polygon into one of the above
  78597. // four classes.
  78598. var polygonType = 0;
  78599. var types = [];
  78600. var i;
  78601. var t;
  78602. for (i = 0; i < polygon.vertices.length; i++) {
  78603. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  78604. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  78605. polygonType |= type;
  78606. types.push(type);
  78607. }
  78608. // Put the polygon in the correct list, splitting it when necessary.
  78609. switch (polygonType) {
  78610. case COPLANAR:
  78611. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  78612. break;
  78613. case FRONT:
  78614. front.push(polygon);
  78615. break;
  78616. case BACK:
  78617. back.push(polygon);
  78618. break;
  78619. case SPANNING:
  78620. var f = [], b = [];
  78621. for (i = 0; i < polygon.vertices.length; i++) {
  78622. var j = (i + 1) % polygon.vertices.length;
  78623. var ti = types[i], tj = types[j];
  78624. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  78625. if (ti !== BACK)
  78626. f.push(vi);
  78627. if (ti !== FRONT)
  78628. b.push(ti !== BACK ? vi.clone() : vi);
  78629. if ((ti | tj) === SPANNING) {
  78630. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  78631. var v = vi.interpolate(vj, t);
  78632. f.push(v);
  78633. b.push(v.clone());
  78634. }
  78635. }
  78636. var poly;
  78637. if (f.length >= 3) {
  78638. poly = new Polygon(f, polygon.shared);
  78639. if (poly.plane)
  78640. front.push(poly);
  78641. }
  78642. if (b.length >= 3) {
  78643. poly = new Polygon(b, polygon.shared);
  78644. if (poly.plane)
  78645. back.push(poly);
  78646. }
  78647. break;
  78648. }
  78649. };
  78650. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  78651. // point is on the plane.
  78652. Plane.EPSILON = 1e-5;
  78653. return Plane;
  78654. }());
  78655. // # class Polygon
  78656. // Represents a convex polygon. The vertices used to initialize a polygon must
  78657. // be coplanar and form a convex loop.
  78658. //
  78659. // Each convex polygon has a `shared` property, which is shared between all
  78660. // polygons that are clones of each other or were split from the same polygon.
  78661. // This can be used to define per-polygon properties (such as surface color).
  78662. var Polygon = /** @class */ (function () {
  78663. function Polygon(vertices, shared) {
  78664. this.vertices = vertices;
  78665. this.shared = shared;
  78666. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  78667. }
  78668. Polygon.prototype.clone = function () {
  78669. var vertices = this.vertices.map(function (v) { return v.clone(); });
  78670. return new Polygon(vertices, this.shared);
  78671. };
  78672. Polygon.prototype.flip = function () {
  78673. this.vertices.reverse().map(function (v) { v.flip(); });
  78674. this.plane.flip();
  78675. };
  78676. return Polygon;
  78677. }());
  78678. // # class Node
  78679. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  78680. // by picking a polygon to split along. That polygon (and all other coplanar
  78681. // polygons) are added directly to that node and the other polygons are added to
  78682. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  78683. // no distinction between internal and leaf nodes.
  78684. var Node = /** @class */ (function () {
  78685. function Node(polygons) {
  78686. this.plane = null;
  78687. this.front = null;
  78688. this.back = null;
  78689. this.polygons = new Array();
  78690. if (polygons) {
  78691. this.build(polygons);
  78692. }
  78693. }
  78694. Node.prototype.clone = function () {
  78695. var node = new Node();
  78696. node.plane = this.plane && this.plane.clone();
  78697. node.front = this.front && this.front.clone();
  78698. node.back = this.back && this.back.clone();
  78699. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  78700. return node;
  78701. };
  78702. // Convert solid space to empty space and empty space to solid space.
  78703. Node.prototype.invert = function () {
  78704. for (var i = 0; i < this.polygons.length; i++) {
  78705. this.polygons[i].flip();
  78706. }
  78707. if (this.plane) {
  78708. this.plane.flip();
  78709. }
  78710. if (this.front) {
  78711. this.front.invert();
  78712. }
  78713. if (this.back) {
  78714. this.back.invert();
  78715. }
  78716. var temp = this.front;
  78717. this.front = this.back;
  78718. this.back = temp;
  78719. };
  78720. // Recursively remove all polygons in `polygons` that are inside this BSP
  78721. // tree.
  78722. Node.prototype.clipPolygons = function (polygons) {
  78723. if (!this.plane)
  78724. return polygons.slice();
  78725. var front = new Array(), back = new Array();
  78726. for (var i = 0; i < polygons.length; i++) {
  78727. this.plane.splitPolygon(polygons[i], front, back, front, back);
  78728. }
  78729. if (this.front) {
  78730. front = this.front.clipPolygons(front);
  78731. }
  78732. if (this.back) {
  78733. back = this.back.clipPolygons(back);
  78734. }
  78735. else {
  78736. back = [];
  78737. }
  78738. return front.concat(back);
  78739. };
  78740. // Remove all polygons in this BSP tree that are inside the other BSP tree
  78741. // `bsp`.
  78742. Node.prototype.clipTo = function (bsp) {
  78743. this.polygons = bsp.clipPolygons(this.polygons);
  78744. if (this.front)
  78745. this.front.clipTo(bsp);
  78746. if (this.back)
  78747. this.back.clipTo(bsp);
  78748. };
  78749. // Return a list of all polygons in this BSP tree.
  78750. Node.prototype.allPolygons = function () {
  78751. var polygons = this.polygons.slice();
  78752. if (this.front)
  78753. polygons = polygons.concat(this.front.allPolygons());
  78754. if (this.back)
  78755. polygons = polygons.concat(this.back.allPolygons());
  78756. return polygons;
  78757. };
  78758. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  78759. // new polygons are filtered down to the bottom of the tree and become new
  78760. // nodes there. Each set of polygons is partitioned using the first polygon
  78761. // (no heuristic is used to pick a good split).
  78762. Node.prototype.build = function (polygons) {
  78763. if (!polygons.length)
  78764. return;
  78765. if (!this.plane)
  78766. this.plane = polygons[0].plane.clone();
  78767. var front = new Array(), back = new Array();
  78768. for (var i = 0; i < polygons.length; i++) {
  78769. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  78770. }
  78771. if (front.length) {
  78772. if (!this.front)
  78773. this.front = new Node();
  78774. this.front.build(front);
  78775. }
  78776. if (back.length) {
  78777. if (!this.back)
  78778. this.back = new Node();
  78779. this.back.build(back);
  78780. }
  78781. };
  78782. return Node;
  78783. }());
  78784. var CSG = /** @class */ (function () {
  78785. function CSG() {
  78786. this.polygons = new Array();
  78787. }
  78788. // Convert BABYLON.Mesh to BABYLON.CSG
  78789. CSG.FromMesh = function (mesh) {
  78790. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  78791. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  78792. if (mesh instanceof BABYLON.Mesh) {
  78793. mesh.computeWorldMatrix(true);
  78794. matrix = mesh.getWorldMatrix();
  78795. meshPosition = mesh.position.clone();
  78796. meshRotation = mesh.rotation.clone();
  78797. if (mesh.rotationQuaternion) {
  78798. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  78799. }
  78800. meshScaling = mesh.scaling.clone();
  78801. }
  78802. else {
  78803. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  78804. }
  78805. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78806. var subMeshes = mesh.subMeshes;
  78807. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  78808. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  78809. vertices = [];
  78810. for (var j = 0; j < 3; j++) {
  78811. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  78812. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  78813. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  78814. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  78815. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  78816. vertex = new Vertex(position, normal, uv);
  78817. vertices.push(vertex);
  78818. }
  78819. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  78820. // To handle the case of degenerated triangle
  78821. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  78822. if (polygon.plane)
  78823. polygons.push(polygon);
  78824. }
  78825. }
  78826. var csg = CSG.FromPolygons(polygons);
  78827. csg.matrix = matrix;
  78828. csg.position = meshPosition;
  78829. csg.rotation = meshRotation;
  78830. csg.scaling = meshScaling;
  78831. csg.rotationQuaternion = meshRotationQuaternion;
  78832. currentCSGMeshId++;
  78833. return csg;
  78834. };
  78835. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  78836. CSG.FromPolygons = function (polygons) {
  78837. var csg = new CSG();
  78838. csg.polygons = polygons;
  78839. return csg;
  78840. };
  78841. CSG.prototype.clone = function () {
  78842. var csg = new CSG();
  78843. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  78844. csg.copyTransformAttributes(this);
  78845. return csg;
  78846. };
  78847. CSG.prototype.union = function (csg) {
  78848. var a = new Node(this.clone().polygons);
  78849. var b = new Node(csg.clone().polygons);
  78850. a.clipTo(b);
  78851. b.clipTo(a);
  78852. b.invert();
  78853. b.clipTo(a);
  78854. b.invert();
  78855. a.build(b.allPolygons());
  78856. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78857. };
  78858. CSG.prototype.unionInPlace = function (csg) {
  78859. var a = new Node(this.polygons);
  78860. var b = new Node(csg.polygons);
  78861. a.clipTo(b);
  78862. b.clipTo(a);
  78863. b.invert();
  78864. b.clipTo(a);
  78865. b.invert();
  78866. a.build(b.allPolygons());
  78867. this.polygons = a.allPolygons();
  78868. };
  78869. CSG.prototype.subtract = function (csg) {
  78870. var a = new Node(this.clone().polygons);
  78871. var b = new Node(csg.clone().polygons);
  78872. a.invert();
  78873. a.clipTo(b);
  78874. b.clipTo(a);
  78875. b.invert();
  78876. b.clipTo(a);
  78877. b.invert();
  78878. a.build(b.allPolygons());
  78879. a.invert();
  78880. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78881. };
  78882. CSG.prototype.subtractInPlace = function (csg) {
  78883. var a = new Node(this.polygons);
  78884. var b = new Node(csg.polygons);
  78885. a.invert();
  78886. a.clipTo(b);
  78887. b.clipTo(a);
  78888. b.invert();
  78889. b.clipTo(a);
  78890. b.invert();
  78891. a.build(b.allPolygons());
  78892. a.invert();
  78893. this.polygons = a.allPolygons();
  78894. };
  78895. CSG.prototype.intersect = function (csg) {
  78896. var a = new Node(this.clone().polygons);
  78897. var b = new Node(csg.clone().polygons);
  78898. a.invert();
  78899. b.clipTo(a);
  78900. b.invert();
  78901. a.clipTo(b);
  78902. b.clipTo(a);
  78903. a.build(b.allPolygons());
  78904. a.invert();
  78905. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78906. };
  78907. CSG.prototype.intersectInPlace = function (csg) {
  78908. var a = new Node(this.polygons);
  78909. var b = new Node(csg.polygons);
  78910. a.invert();
  78911. b.clipTo(a);
  78912. b.invert();
  78913. a.clipTo(b);
  78914. b.clipTo(a);
  78915. a.build(b.allPolygons());
  78916. a.invert();
  78917. this.polygons = a.allPolygons();
  78918. };
  78919. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  78920. // not modified.
  78921. CSG.prototype.inverse = function () {
  78922. var csg = this.clone();
  78923. csg.inverseInPlace();
  78924. return csg;
  78925. };
  78926. CSG.prototype.inverseInPlace = function () {
  78927. this.polygons.map(function (p) { p.flip(); });
  78928. };
  78929. // This is used to keep meshes transformations so they can be restored
  78930. // when we build back a Babylon Mesh
  78931. // NB : All CSG operations are performed in world coordinates
  78932. CSG.prototype.copyTransformAttributes = function (csg) {
  78933. this.matrix = csg.matrix;
  78934. this.position = csg.position;
  78935. this.rotation = csg.rotation;
  78936. this.scaling = csg.scaling;
  78937. this.rotationQuaternion = csg.rotationQuaternion;
  78938. return this;
  78939. };
  78940. // Build Raw mesh from CSG
  78941. // Coordinates here are in world space
  78942. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  78943. var matrix = this.matrix.clone();
  78944. matrix.invert();
  78945. 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;
  78946. if (keepSubMeshes) {
  78947. // Sort Polygons, since subMeshes are indices range
  78948. polygons.sort(function (a, b) {
  78949. if (a.shared.meshId === b.shared.meshId) {
  78950. return a.shared.subMeshId - b.shared.subMeshId;
  78951. }
  78952. else {
  78953. return a.shared.meshId - b.shared.meshId;
  78954. }
  78955. });
  78956. }
  78957. for (var i = 0, il = polygons.length; i < il; i++) {
  78958. polygon = polygons[i];
  78959. // Building SubMeshes
  78960. if (!subMesh_dict[polygon.shared.meshId]) {
  78961. subMesh_dict[polygon.shared.meshId] = {};
  78962. }
  78963. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  78964. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  78965. indexStart: +Infinity,
  78966. indexEnd: -Infinity,
  78967. materialIndex: polygon.shared.materialIndex
  78968. };
  78969. }
  78970. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  78971. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  78972. polygonIndices[0] = 0;
  78973. polygonIndices[1] = j - 1;
  78974. polygonIndices[2] = j;
  78975. for (var k = 0; k < 3; k++) {
  78976. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  78977. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  78978. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  78979. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  78980. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  78981. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  78982. // Check if 2 points can be merged
  78983. if (!(typeof vertex_idx !== 'undefined' &&
  78984. normals[vertex_idx * 3] === localNormal.x &&
  78985. normals[vertex_idx * 3 + 1] === localNormal.y &&
  78986. normals[vertex_idx * 3 + 2] === localNormal.z &&
  78987. uvs[vertex_idx * 2] === uv.x &&
  78988. uvs[vertex_idx * 2 + 1] === uv.y)) {
  78989. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  78990. uvs.push(uv.x, uv.y);
  78991. normals.push(normal.x, normal.y, normal.z);
  78992. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  78993. }
  78994. indices.push(vertex_idx);
  78995. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  78996. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  78997. currentIndex++;
  78998. }
  78999. }
  79000. }
  79001. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  79002. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  79003. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  79004. mesh.setIndices(indices, null);
  79005. if (keepSubMeshes) {
  79006. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  79007. var materialIndexOffset = 0, materialMaxIndex;
  79008. mesh.subMeshes = new Array();
  79009. for (var m in subMesh_dict) {
  79010. materialMaxIndex = -1;
  79011. for (var sm in subMesh_dict[m]) {
  79012. subMesh_obj = subMesh_dict[m][sm];
  79013. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  79014. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  79015. }
  79016. materialIndexOffset += ++materialMaxIndex;
  79017. }
  79018. }
  79019. return mesh;
  79020. };
  79021. // Build Mesh from CSG taking material and transforms into account
  79022. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  79023. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  79024. mesh.material = material;
  79025. mesh.position.copyFrom(this.position);
  79026. mesh.rotation.copyFrom(this.rotation);
  79027. if (this.rotationQuaternion) {
  79028. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  79029. }
  79030. mesh.scaling.copyFrom(this.scaling);
  79031. mesh.computeWorldMatrix(true);
  79032. return mesh;
  79033. };
  79034. return CSG;
  79035. }());
  79036. BABYLON.CSG = CSG;
  79037. })(BABYLON || (BABYLON = {}));
  79038. //# sourceMappingURL=babylon.csg.js.map
  79039. "use strict";
  79040. var BABYLON;
  79041. (function (BABYLON) {
  79042. var LensFlare = /** @class */ (function () {
  79043. function LensFlare(size, position, color, imgUrl, system) {
  79044. this.size = size;
  79045. this.position = position;
  79046. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79047. this.color = color || new BABYLON.Color3(1, 1, 1);
  79048. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  79049. this._system = system;
  79050. system.lensFlares.push(this);
  79051. }
  79052. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  79053. return new LensFlare(size, position, color, imgUrl, system);
  79054. };
  79055. LensFlare.prototype.dispose = function () {
  79056. if (this.texture) {
  79057. this.texture.dispose();
  79058. }
  79059. // Remove from scene
  79060. var index = this._system.lensFlares.indexOf(this);
  79061. this._system.lensFlares.splice(index, 1);
  79062. };
  79063. ;
  79064. return LensFlare;
  79065. }());
  79066. BABYLON.LensFlare = LensFlare;
  79067. })(BABYLON || (BABYLON = {}));
  79068. //# sourceMappingURL=babylon.lensFlare.js.map
  79069. "use strict";
  79070. var BABYLON;
  79071. (function (BABYLON) {
  79072. var LensFlareSystem = /** @class */ (function () {
  79073. function LensFlareSystem(name, emitter, scene) {
  79074. this.name = name;
  79075. this.lensFlares = new Array();
  79076. this.borderLimit = 300;
  79077. this.viewportBorder = 0;
  79078. this.layerMask = 0x0FFFFFFF;
  79079. this._vertexBuffers = {};
  79080. this._isEnabled = true;
  79081. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79082. this._emitter = emitter;
  79083. this.id = name;
  79084. scene.lensFlareSystems.push(this);
  79085. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  79086. var engine = scene.getEngine();
  79087. // VBO
  79088. var vertices = [];
  79089. vertices.push(1, 1);
  79090. vertices.push(-1, 1);
  79091. vertices.push(-1, -1);
  79092. vertices.push(1, -1);
  79093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79094. // Indices
  79095. var indices = [];
  79096. indices.push(0);
  79097. indices.push(1);
  79098. indices.push(2);
  79099. indices.push(0);
  79100. indices.push(2);
  79101. indices.push(3);
  79102. this._indexBuffer = engine.createIndexBuffer(indices);
  79103. // Effects
  79104. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  79105. }
  79106. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  79107. get: function () {
  79108. return this._isEnabled;
  79109. },
  79110. set: function (value) {
  79111. this._isEnabled = value;
  79112. },
  79113. enumerable: true,
  79114. configurable: true
  79115. });
  79116. LensFlareSystem.prototype.getScene = function () {
  79117. return this._scene;
  79118. };
  79119. LensFlareSystem.prototype.getEmitter = function () {
  79120. return this._emitter;
  79121. };
  79122. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79123. this._emitter = newEmitter;
  79124. };
  79125. LensFlareSystem.prototype.getEmitterPosition = function () {
  79126. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79127. };
  79128. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79129. var position = this.getEmitterPosition();
  79130. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79131. this._positionX = position.x;
  79132. this._positionY = position.y;
  79133. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79134. if (this.viewportBorder > 0) {
  79135. globalViewport.x -= this.viewportBorder;
  79136. globalViewport.y -= this.viewportBorder;
  79137. globalViewport.width += this.viewportBorder * 2;
  79138. globalViewport.height += this.viewportBorder * 2;
  79139. position.x += this.viewportBorder;
  79140. position.y += this.viewportBorder;
  79141. this._positionX += this.viewportBorder;
  79142. this._positionY += this.viewportBorder;
  79143. }
  79144. if (position.z > 0) {
  79145. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79146. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79147. return true;
  79148. }
  79149. return true;
  79150. }
  79151. return false;
  79152. };
  79153. LensFlareSystem.prototype._isVisible = function () {
  79154. if (!this._isEnabled || !this._scene.activeCamera) {
  79155. return false;
  79156. }
  79157. var emitterPosition = this.getEmitterPosition();
  79158. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79159. var distance = direction.length();
  79160. direction.normalize();
  79161. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79162. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79163. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79164. };
  79165. LensFlareSystem.prototype.render = function () {
  79166. if (!this._effect.isReady() || !this._scene.activeCamera)
  79167. return false;
  79168. var engine = this._scene.getEngine();
  79169. var viewport = this._scene.activeCamera.viewport;
  79170. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79171. // Position
  79172. if (!this.computeEffectivePosition(globalViewport)) {
  79173. return false;
  79174. }
  79175. // Visibility
  79176. if (!this._isVisible()) {
  79177. return false;
  79178. }
  79179. // Intensity
  79180. var awayX;
  79181. var awayY;
  79182. if (this._positionX < this.borderLimit + globalViewport.x) {
  79183. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79184. }
  79185. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79186. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79187. }
  79188. else {
  79189. awayX = 0;
  79190. }
  79191. if (this._positionY < this.borderLimit + globalViewport.y) {
  79192. awayY = this.borderLimit + globalViewport.y - this._positionY;
  79193. }
  79194. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  79195. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  79196. }
  79197. else {
  79198. awayY = 0;
  79199. }
  79200. var away = (awayX > awayY) ? awayX : awayY;
  79201. away -= this.viewportBorder;
  79202. if (away > this.borderLimit) {
  79203. away = this.borderLimit;
  79204. }
  79205. var intensity = 1.0 - (away / this.borderLimit);
  79206. if (intensity < 0) {
  79207. return false;
  79208. }
  79209. if (intensity > 1.0) {
  79210. intensity = 1.0;
  79211. }
  79212. if (this.viewportBorder > 0) {
  79213. globalViewport.x += this.viewportBorder;
  79214. globalViewport.y += this.viewportBorder;
  79215. globalViewport.width -= this.viewportBorder * 2;
  79216. globalViewport.height -= this.viewportBorder * 2;
  79217. this._positionX -= this.viewportBorder;
  79218. this._positionY -= this.viewportBorder;
  79219. }
  79220. // Position
  79221. var centerX = globalViewport.x + globalViewport.width / 2;
  79222. var centerY = globalViewport.y + globalViewport.height / 2;
  79223. var distX = centerX - this._positionX;
  79224. var distY = centerY - this._positionY;
  79225. // Effects
  79226. engine.enableEffect(this._effect);
  79227. engine.setState(false);
  79228. engine.setDepthBuffer(false);
  79229. // VBOs
  79230. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79231. // Flares
  79232. for (var index = 0; index < this.lensFlares.length; index++) {
  79233. var flare = this.lensFlares[index];
  79234. engine.setAlphaMode(flare.alphaMode);
  79235. var x = centerX - (distX * flare.position);
  79236. var y = centerY - (distY * flare.position);
  79237. var cw = flare.size;
  79238. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  79239. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  79240. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  79241. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  79242. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  79243. // Texture
  79244. this._effect.setTexture("textureSampler", flare.texture);
  79245. // Color
  79246. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  79247. // Draw order
  79248. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79249. }
  79250. engine.setDepthBuffer(true);
  79251. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79252. return true;
  79253. };
  79254. LensFlareSystem.prototype.dispose = function () {
  79255. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79256. if (vertexBuffer) {
  79257. vertexBuffer.dispose();
  79258. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79259. }
  79260. if (this._indexBuffer) {
  79261. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79262. this._indexBuffer = null;
  79263. }
  79264. while (this.lensFlares.length) {
  79265. this.lensFlares[0].dispose();
  79266. }
  79267. // Remove from scene
  79268. var index = this._scene.lensFlareSystems.indexOf(this);
  79269. this._scene.lensFlareSystems.splice(index, 1);
  79270. };
  79271. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  79272. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  79273. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  79274. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  79275. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  79276. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  79277. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  79278. var parsedFlare = parsedLensFlareSystem.flares[index];
  79279. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  79280. }
  79281. return lensFlareSystem;
  79282. };
  79283. LensFlareSystem.prototype.serialize = function () {
  79284. var serializationObject = {};
  79285. serializationObject.id = this.id;
  79286. serializationObject.name = this.name;
  79287. serializationObject.emitterId = this.getEmitter().id;
  79288. serializationObject.borderLimit = this.borderLimit;
  79289. serializationObject.flares = [];
  79290. for (var index = 0; index < this.lensFlares.length; index++) {
  79291. var flare = this.lensFlares[index];
  79292. serializationObject.flares.push({
  79293. size: flare.size,
  79294. position: flare.position,
  79295. color: flare.color.asArray(),
  79296. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  79297. });
  79298. }
  79299. return serializationObject;
  79300. };
  79301. return LensFlareSystem;
  79302. }());
  79303. BABYLON.LensFlareSystem = LensFlareSystem;
  79304. })(BABYLON || (BABYLON = {}));
  79305. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  79306. "use strict";
  79307. var BABYLON;
  79308. (function (BABYLON) {
  79309. /**
  79310. * This is a holder class for the physics joint created by the physics plugin.
  79311. * It holds a set of functions to control the underlying joint.
  79312. */
  79313. var PhysicsJoint = /** @class */ (function () {
  79314. function PhysicsJoint(type, jointData) {
  79315. this.type = type;
  79316. this.jointData = jointData;
  79317. jointData.nativeParams = jointData.nativeParams || {};
  79318. }
  79319. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  79320. get: function () {
  79321. return this._physicsJoint;
  79322. },
  79323. set: function (newJoint) {
  79324. if (this._physicsJoint) {
  79325. //remove from the wolrd
  79326. }
  79327. this._physicsJoint = newJoint;
  79328. },
  79329. enumerable: true,
  79330. configurable: true
  79331. });
  79332. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  79333. set: function (physicsPlugin) {
  79334. this._physicsPlugin = physicsPlugin;
  79335. },
  79336. enumerable: true,
  79337. configurable: true
  79338. });
  79339. /**
  79340. * Execute a function that is physics-plugin specific.
  79341. * @param {Function} func the function that will be executed.
  79342. * It accepts two parameters: the physics world and the physics joint.
  79343. */
  79344. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  79345. func(this._physicsPlugin.world, this._physicsJoint);
  79346. };
  79347. //TODO check if the native joints are the same
  79348. //Joint Types
  79349. PhysicsJoint.DistanceJoint = 0;
  79350. PhysicsJoint.HingeJoint = 1;
  79351. PhysicsJoint.BallAndSocketJoint = 2;
  79352. PhysicsJoint.WheelJoint = 3;
  79353. PhysicsJoint.SliderJoint = 4;
  79354. //OIMO
  79355. PhysicsJoint.PrismaticJoint = 5;
  79356. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  79357. PhysicsJoint.UniversalJoint = 6;
  79358. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  79359. //Cannon
  79360. //Similar to a Ball-Joint. Different in params
  79361. PhysicsJoint.PointToPointJoint = 8;
  79362. //Cannon only at the moment
  79363. PhysicsJoint.SpringJoint = 9;
  79364. PhysicsJoint.LockJoint = 10;
  79365. return PhysicsJoint;
  79366. }());
  79367. BABYLON.PhysicsJoint = PhysicsJoint;
  79368. /**
  79369. * A class representing a physics distance joint.
  79370. */
  79371. var DistanceJoint = /** @class */ (function (_super) {
  79372. __extends(DistanceJoint, _super);
  79373. function DistanceJoint(jointData) {
  79374. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  79375. }
  79376. /**
  79377. * Update the predefined distance.
  79378. */
  79379. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  79380. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  79381. };
  79382. return DistanceJoint;
  79383. }(PhysicsJoint));
  79384. BABYLON.DistanceJoint = DistanceJoint;
  79385. var MotorEnabledJoint = /** @class */ (function (_super) {
  79386. __extends(MotorEnabledJoint, _super);
  79387. function MotorEnabledJoint(type, jointData) {
  79388. return _super.call(this, type, jointData) || this;
  79389. }
  79390. /**
  79391. * Set the motor values.
  79392. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79393. * @param {number} force the force to apply
  79394. * @param {number} maxForce max force for this motor.
  79395. */
  79396. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  79397. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79398. };
  79399. /**
  79400. * Set the motor's limits.
  79401. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79402. */
  79403. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79404. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79405. };
  79406. return MotorEnabledJoint;
  79407. }(PhysicsJoint));
  79408. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  79409. /**
  79410. * This class represents a single hinge physics joint
  79411. */
  79412. var HingeJoint = /** @class */ (function (_super) {
  79413. __extends(HingeJoint, _super);
  79414. function HingeJoint(jointData) {
  79415. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  79416. }
  79417. /**
  79418. * Set the motor values.
  79419. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79420. * @param {number} force the force to apply
  79421. * @param {number} maxForce max force for this motor.
  79422. */
  79423. HingeJoint.prototype.setMotor = function (force, maxForce) {
  79424. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79425. };
  79426. /**
  79427. * Set the motor's limits.
  79428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79429. */
  79430. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79431. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79432. };
  79433. return HingeJoint;
  79434. }(MotorEnabledJoint));
  79435. BABYLON.HingeJoint = HingeJoint;
  79436. /**
  79437. * This class represents a dual hinge physics joint (same as wheel joint)
  79438. */
  79439. var Hinge2Joint = /** @class */ (function (_super) {
  79440. __extends(Hinge2Joint, _super);
  79441. function Hinge2Joint(jointData) {
  79442. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  79443. }
  79444. /**
  79445. * Set the motor values.
  79446. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79447. * @param {number} force the force to apply
  79448. * @param {number} maxForce max force for this motor.
  79449. * @param {motorIndex} the motor's index, 0 or 1.
  79450. */
  79451. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  79452. if (motorIndex === void 0) { motorIndex = 0; }
  79453. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  79454. };
  79455. /**
  79456. * Set the motor limits.
  79457. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79458. * @param {number} upperLimit the upper limit
  79459. * @param {number} lowerLimit lower limit
  79460. * @param {motorIndex} the motor's index, 0 or 1.
  79461. */
  79462. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  79463. if (motorIndex === void 0) { motorIndex = 0; }
  79464. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  79465. };
  79466. return Hinge2Joint;
  79467. }(MotorEnabledJoint));
  79468. BABYLON.Hinge2Joint = Hinge2Joint;
  79469. })(BABYLON || (BABYLON = {}));
  79470. //# sourceMappingURL=babylon.physicsJoint.js.map
  79471. "use strict";
  79472. var BABYLON;
  79473. (function (BABYLON) {
  79474. var PhysicsImpostor = /** @class */ (function () {
  79475. function PhysicsImpostor(object, type, _options, _scene) {
  79476. if (_options === void 0) { _options = { mass: 0 }; }
  79477. var _this = this;
  79478. this.object = object;
  79479. this.type = type;
  79480. this._options = _options;
  79481. this._scene = _scene;
  79482. this._bodyUpdateRequired = false;
  79483. this._onBeforePhysicsStepCallbacks = new Array();
  79484. this._onAfterPhysicsStepCallbacks = new Array();
  79485. this._onPhysicsCollideCallbacks = [];
  79486. this._deltaPosition = BABYLON.Vector3.Zero();
  79487. this._isDisposed = false;
  79488. //temp variables for parent rotation calculations
  79489. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  79490. this._tmpQuat = new BABYLON.Quaternion();
  79491. this._tmpQuat2 = new BABYLON.Quaternion();
  79492. /**
  79493. * this function is executed by the physics engine.
  79494. */
  79495. this.beforeStep = function () {
  79496. if (!_this._physicsEngine) {
  79497. return;
  79498. }
  79499. _this.object.translate(_this._deltaPosition, -1);
  79500. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  79501. _this.object.computeWorldMatrix(false);
  79502. if (_this.object.parent && _this.object.rotationQuaternion) {
  79503. _this.getParentsRotation();
  79504. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  79505. }
  79506. else {
  79507. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  79508. }
  79509. if (!_this._options.disableBidirectionalTransformation) {
  79510. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  79511. }
  79512. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  79513. func(_this);
  79514. });
  79515. };
  79516. /**
  79517. * this function is executed by the physics engine.
  79518. */
  79519. this.afterStep = function () {
  79520. if (!_this._physicsEngine) {
  79521. return;
  79522. }
  79523. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  79524. func(_this);
  79525. });
  79526. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  79527. // object has now its world rotation. needs to be converted to local.
  79528. if (_this.object.parent && _this.object.rotationQuaternion) {
  79529. _this.getParentsRotation();
  79530. _this._tmpQuat.conjugateInPlace();
  79531. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  79532. }
  79533. // take the position set and make it the absolute position of this object.
  79534. _this.object.setAbsolutePosition(_this.object.position);
  79535. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  79536. _this.object.translate(_this._deltaPosition, 1);
  79537. };
  79538. /**
  79539. * Legacy collision detection event support
  79540. */
  79541. this.onCollideEvent = null;
  79542. //event and body object due to cannon's event-based architecture.
  79543. this.onCollide = function (e) {
  79544. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  79545. return;
  79546. }
  79547. if (!_this._physicsEngine) {
  79548. return;
  79549. }
  79550. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  79551. if (otherImpostor) {
  79552. // Legacy collision detection event support
  79553. if (_this.onCollideEvent) {
  79554. _this.onCollideEvent(_this, otherImpostor);
  79555. }
  79556. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  79557. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  79558. }).forEach(function (obj) {
  79559. obj.callback(_this, otherImpostor);
  79560. });
  79561. }
  79562. };
  79563. //sanity check!
  79564. if (!this.object) {
  79565. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  79566. return;
  79567. }
  79568. //legacy support for old syntax.
  79569. if (!this._scene && object.getScene) {
  79570. this._scene = object.getScene();
  79571. }
  79572. if (!this._scene) {
  79573. return;
  79574. }
  79575. this._physicsEngine = this._scene.getPhysicsEngine();
  79576. if (!this._physicsEngine) {
  79577. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  79578. }
  79579. else {
  79580. //set the object's quaternion, if not set
  79581. if (!this.object.rotationQuaternion) {
  79582. if (this.object.rotation) {
  79583. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  79584. }
  79585. else {
  79586. this.object.rotationQuaternion = new BABYLON.Quaternion();
  79587. }
  79588. }
  79589. //default options params
  79590. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  79591. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  79592. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  79593. this._joints = [];
  79594. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  79595. if (!this.object.parent || this._options.ignoreParent) {
  79596. this._init();
  79597. }
  79598. else if (this.object.parent.physicsImpostor) {
  79599. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  79600. }
  79601. }
  79602. }
  79603. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  79604. get: function () {
  79605. return this._isDisposed;
  79606. },
  79607. enumerable: true,
  79608. configurable: true
  79609. });
  79610. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  79611. get: function () {
  79612. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  79613. },
  79614. set: function (value) {
  79615. this.setMass(value);
  79616. },
  79617. enumerable: true,
  79618. configurable: true
  79619. });
  79620. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  79621. get: function () {
  79622. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  79623. },
  79624. set: function (value) {
  79625. if (!this._physicsEngine) {
  79626. return;
  79627. }
  79628. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  79629. },
  79630. enumerable: true,
  79631. configurable: true
  79632. });
  79633. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  79634. get: function () {
  79635. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  79636. },
  79637. set: function (value) {
  79638. if (!this._physicsEngine) {
  79639. return;
  79640. }
  79641. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  79642. },
  79643. enumerable: true,
  79644. configurable: true
  79645. });
  79646. /**
  79647. * This function will completly initialize this impostor.
  79648. * It will create a new body - but only if this mesh has no parent.
  79649. * If it has, this impostor will not be used other than to define the impostor
  79650. * of the child mesh.
  79651. */
  79652. PhysicsImpostor.prototype._init = function () {
  79653. if (!this._physicsEngine) {
  79654. return;
  79655. }
  79656. this._physicsEngine.removeImpostor(this);
  79657. this.physicsBody = null;
  79658. this._parent = this._parent || this._getPhysicsParent();
  79659. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  79660. this._physicsEngine.addImpostor(this);
  79661. }
  79662. };
  79663. PhysicsImpostor.prototype._getPhysicsParent = function () {
  79664. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  79665. var parentMesh = this.object.parent;
  79666. return parentMesh.physicsImpostor;
  79667. }
  79668. return null;
  79669. };
  79670. /**
  79671. * Should a new body be generated.
  79672. */
  79673. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  79674. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  79675. };
  79676. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  79677. this.forceUpdate();
  79678. };
  79679. /**
  79680. * Force a regeneration of this or the parent's impostor's body.
  79681. * Use under cautious - This will remove all joints already implemented.
  79682. */
  79683. PhysicsImpostor.prototype.forceUpdate = function () {
  79684. this._init();
  79685. if (this.parent && !this._options.ignoreParent) {
  79686. this.parent.forceUpdate();
  79687. }
  79688. };
  79689. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  79690. /*public get mesh(): AbstractMesh {
  79691. return this._mesh;
  79692. }*/
  79693. /**
  79694. * Gets the body that holds this impostor. Either its own, or its parent.
  79695. */
  79696. get: function () {
  79697. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  79698. },
  79699. /**
  79700. * Set the physics body. Used mainly by the physics engine/plugin
  79701. */
  79702. set: function (physicsBody) {
  79703. if (this._physicsBody && this._physicsEngine) {
  79704. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  79705. }
  79706. this._physicsBody = physicsBody;
  79707. this.resetUpdateFlags();
  79708. },
  79709. enumerable: true,
  79710. configurable: true
  79711. });
  79712. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  79713. get: function () {
  79714. return !this._options.ignoreParent && this._parent ? this._parent : null;
  79715. },
  79716. set: function (value) {
  79717. this._parent = value;
  79718. },
  79719. enumerable: true,
  79720. configurable: true
  79721. });
  79722. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  79723. this._bodyUpdateRequired = false;
  79724. };
  79725. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  79726. if (this.object.getBoundingInfo) {
  79727. var q = this.object.rotationQuaternion;
  79728. //reset rotation
  79729. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  79730. //calculate the world matrix with no rotation
  79731. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  79732. var boundingInfo = this.object.getBoundingInfo();
  79733. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  79734. //bring back the rotation
  79735. this.object.rotationQuaternion = q;
  79736. //calculate the world matrix with the new rotation
  79737. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  79738. return size;
  79739. }
  79740. else {
  79741. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  79742. }
  79743. };
  79744. PhysicsImpostor.prototype.getObjectCenter = function () {
  79745. if (this.object.getBoundingInfo) {
  79746. var boundingInfo = this.object.getBoundingInfo();
  79747. return boundingInfo.boundingBox.centerWorld;
  79748. }
  79749. else {
  79750. return this.object.position;
  79751. }
  79752. };
  79753. /**
  79754. * Get a specific parametes from the options parameter.
  79755. */
  79756. PhysicsImpostor.prototype.getParam = function (paramName) {
  79757. return this._options[paramName];
  79758. };
  79759. /**
  79760. * Sets a specific parameter in the options given to the physics plugin
  79761. */
  79762. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  79763. this._options[paramName] = value;
  79764. this._bodyUpdateRequired = true;
  79765. };
  79766. /**
  79767. * Specifically change the body's mass option. Won't recreate the physics body object
  79768. */
  79769. PhysicsImpostor.prototype.setMass = function (mass) {
  79770. if (this.getParam("mass") !== mass) {
  79771. this.setParam("mass", mass);
  79772. }
  79773. if (this._physicsEngine) {
  79774. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  79775. }
  79776. };
  79777. PhysicsImpostor.prototype.getLinearVelocity = function () {
  79778. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  79779. };
  79780. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  79781. if (this._physicsEngine) {
  79782. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  79783. }
  79784. };
  79785. PhysicsImpostor.prototype.getAngularVelocity = function () {
  79786. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  79787. };
  79788. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  79789. if (this._physicsEngine) {
  79790. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  79791. }
  79792. };
  79793. /**
  79794. * Execute a function with the physics plugin native code.
  79795. * Provide a function the will have two variables - the world object and the physics body object.
  79796. */
  79797. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  79798. if (this._physicsEngine) {
  79799. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  79800. }
  79801. };
  79802. /**
  79803. * Register a function that will be executed before the physics world is stepping forward.
  79804. */
  79805. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  79806. this._onBeforePhysicsStepCallbacks.push(func);
  79807. };
  79808. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  79809. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  79810. if (index > -1) {
  79811. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  79812. }
  79813. else {
  79814. BABYLON.Tools.Warn("Function to remove was not found");
  79815. }
  79816. };
  79817. /**
  79818. * Register a function that will be executed after the physics step
  79819. */
  79820. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  79821. this._onAfterPhysicsStepCallbacks.push(func);
  79822. };
  79823. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  79824. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  79825. if (index > -1) {
  79826. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  79827. }
  79828. else {
  79829. BABYLON.Tools.Warn("Function to remove was not found");
  79830. }
  79831. };
  79832. /**
  79833. * register a function that will be executed when this impostor collides against a different body.
  79834. */
  79835. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  79836. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  79837. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  79838. };
  79839. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  79840. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  79841. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  79842. if (index > -1) {
  79843. this._onPhysicsCollideCallbacks.splice(index, 1);
  79844. }
  79845. else {
  79846. BABYLON.Tools.Warn("Function to remove was not found");
  79847. }
  79848. };
  79849. PhysicsImpostor.prototype.getParentsRotation = function () {
  79850. var parent = this.object.parent;
  79851. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  79852. while (parent) {
  79853. if (parent.rotationQuaternion) {
  79854. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  79855. }
  79856. else {
  79857. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  79858. }
  79859. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  79860. parent = parent.parent;
  79861. }
  79862. return this._tmpQuat;
  79863. };
  79864. /**
  79865. * Apply a force
  79866. */
  79867. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  79868. if (this._physicsEngine) {
  79869. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  79870. }
  79871. return this;
  79872. };
  79873. /**
  79874. * Apply an impulse
  79875. */
  79876. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  79877. if (this._physicsEngine) {
  79878. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  79879. }
  79880. return this;
  79881. };
  79882. /**
  79883. * A help function to create a joint.
  79884. */
  79885. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  79886. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  79887. this.addJoint(otherImpostor, joint);
  79888. return this;
  79889. };
  79890. /**
  79891. * Add a joint to this impostor with a different impostor.
  79892. */
  79893. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  79894. this._joints.push({
  79895. otherImpostor: otherImpostor,
  79896. joint: joint
  79897. });
  79898. if (this._physicsEngine) {
  79899. this._physicsEngine.addJoint(this, otherImpostor, joint);
  79900. }
  79901. return this;
  79902. };
  79903. /**
  79904. * Will keep this body still, in a sleep mode.
  79905. */
  79906. PhysicsImpostor.prototype.sleep = function () {
  79907. if (this._physicsEngine) {
  79908. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  79909. }
  79910. return this;
  79911. };
  79912. /**
  79913. * Wake the body up.
  79914. */
  79915. PhysicsImpostor.prototype.wakeUp = function () {
  79916. if (this._physicsEngine) {
  79917. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  79918. }
  79919. return this;
  79920. };
  79921. PhysicsImpostor.prototype.clone = function (newObject) {
  79922. if (!newObject)
  79923. return null;
  79924. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  79925. };
  79926. PhysicsImpostor.prototype.dispose = function () {
  79927. var _this = this;
  79928. //no dispose if no physics engine is available.
  79929. if (!this._physicsEngine) {
  79930. return;
  79931. }
  79932. this._joints.forEach(function (j) {
  79933. if (_this._physicsEngine) {
  79934. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  79935. }
  79936. });
  79937. //dispose the physics body
  79938. this._physicsEngine.removeImpostor(this);
  79939. if (this.parent) {
  79940. this.parent.forceUpdate();
  79941. }
  79942. else {
  79943. /*this._object.getChildMeshes().forEach(function(mesh) {
  79944. if (mesh.physicsImpostor) {
  79945. if (disposeChildren) {
  79946. mesh.physicsImpostor.dispose();
  79947. mesh.physicsImpostor = null;
  79948. }
  79949. }
  79950. })*/
  79951. }
  79952. this._isDisposed = true;
  79953. };
  79954. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  79955. this._deltaPosition.copyFrom(position);
  79956. };
  79957. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  79958. if (!this._deltaRotation) {
  79959. this._deltaRotation = new BABYLON.Quaternion();
  79960. }
  79961. this._deltaRotation.copyFrom(rotation);
  79962. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  79963. };
  79964. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  79965. if (this._physicsEngine) {
  79966. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  79967. }
  79968. return this;
  79969. };
  79970. PhysicsImpostor.prototype.getRadius = function () {
  79971. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  79972. };
  79973. /**
  79974. * Sync a bone with this impostor
  79975. * @param bone The bone to sync to the impostor.
  79976. * @param boneMesh The mesh that the bone is influencing.
  79977. * @param jointPivot The pivot of the joint / bone in local space.
  79978. * @param distToJoint Optional distance from the impostor to the joint.
  79979. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  79980. */
  79981. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  79982. var tempVec = PhysicsImpostor._tmpVecs[0];
  79983. var mesh = this.object;
  79984. if (mesh.rotationQuaternion) {
  79985. if (adjustRotation) {
  79986. var tempQuat = PhysicsImpostor._tmpQuat;
  79987. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  79988. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  79989. }
  79990. else {
  79991. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  79992. }
  79993. }
  79994. tempVec.x = 0;
  79995. tempVec.y = 0;
  79996. tempVec.z = 0;
  79997. if (jointPivot) {
  79998. tempVec.x = jointPivot.x;
  79999. tempVec.y = jointPivot.y;
  80000. tempVec.z = jointPivot.z;
  80001. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  80002. if (distToJoint === undefined || distToJoint === null) {
  80003. distToJoint = jointPivot.length();
  80004. }
  80005. tempVec.x *= distToJoint;
  80006. tempVec.y *= distToJoint;
  80007. tempVec.z *= distToJoint;
  80008. }
  80009. if (bone.getParent()) {
  80010. tempVec.addInPlace(mesh.getAbsolutePosition());
  80011. bone.setAbsolutePosition(tempVec, boneMesh);
  80012. }
  80013. else {
  80014. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  80015. boneMesh.position.x -= tempVec.x;
  80016. boneMesh.position.y -= tempVec.y;
  80017. boneMesh.position.z -= tempVec.z;
  80018. }
  80019. };
  80020. /**
  80021. * Sync impostor to a bone
  80022. * @param bone The bone that the impostor will be synced to.
  80023. * @param boneMesh The mesh that the bone is influencing.
  80024. * @param jointPivot The pivot of the joint / bone in local space.
  80025. * @param distToJoint Optional distance from the impostor to the joint.
  80026. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80027. * @param boneAxis Optional vector3 axis the bone is aligned with
  80028. */
  80029. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  80030. var mesh = this.object;
  80031. if (mesh.rotationQuaternion) {
  80032. if (adjustRotation) {
  80033. var tempQuat = PhysicsImpostor._tmpQuat;
  80034. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  80035. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  80036. }
  80037. else {
  80038. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  80039. }
  80040. }
  80041. var pos = PhysicsImpostor._tmpVecs[0];
  80042. var boneDir = PhysicsImpostor._tmpVecs[1];
  80043. if (!boneAxis) {
  80044. boneAxis = PhysicsImpostor._tmpVecs[2];
  80045. boneAxis.x = 0;
  80046. boneAxis.y = 1;
  80047. boneAxis.z = 0;
  80048. }
  80049. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  80050. bone.getAbsolutePositionToRef(boneMesh, pos);
  80051. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  80052. distToJoint = jointPivot.length();
  80053. }
  80054. if (distToJoint !== undefined && distToJoint !== null) {
  80055. pos.x += boneDir.x * distToJoint;
  80056. pos.y += boneDir.y * distToJoint;
  80057. pos.z += boneDir.z * distToJoint;
  80058. }
  80059. mesh.setAbsolutePosition(pos);
  80060. };
  80061. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  80062. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  80063. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80064. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  80065. //Impostor types
  80066. PhysicsImpostor.NoImpostor = 0;
  80067. PhysicsImpostor.SphereImpostor = 1;
  80068. PhysicsImpostor.BoxImpostor = 2;
  80069. PhysicsImpostor.PlaneImpostor = 3;
  80070. PhysicsImpostor.MeshImpostor = 4;
  80071. PhysicsImpostor.CylinderImpostor = 7;
  80072. PhysicsImpostor.ParticleImpostor = 8;
  80073. PhysicsImpostor.HeightmapImpostor = 9;
  80074. return PhysicsImpostor;
  80075. }());
  80076. BABYLON.PhysicsImpostor = PhysicsImpostor;
  80077. })(BABYLON || (BABYLON = {}));
  80078. //# sourceMappingURL=babylon.physicsImpostor.js.map
  80079. "use strict";
  80080. var BABYLON;
  80081. (function (BABYLON) {
  80082. var PhysicsEngine = /** @class */ (function () {
  80083. function PhysicsEngine(gravity, _physicsPlugin) {
  80084. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  80085. this._physicsPlugin = _physicsPlugin;
  80086. //new methods and parameters
  80087. this._impostors = [];
  80088. this._joints = [];
  80089. if (!this._physicsPlugin.isSupported()) {
  80090. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  80091. + "Please make sure it is included.");
  80092. }
  80093. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  80094. this.setGravity(gravity);
  80095. this.setTimeStep();
  80096. }
  80097. PhysicsEngine.prototype.setGravity = function (gravity) {
  80098. this.gravity = gravity;
  80099. this._physicsPlugin.setGravity(this.gravity);
  80100. };
  80101. /**
  80102. * Set the time step of the physics engine.
  80103. * default is 1/60.
  80104. * To slow it down, enter 1/600 for example.
  80105. * To speed it up, 1/30
  80106. * @param {number} newTimeStep the new timestep to apply to this world.
  80107. */
  80108. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80109. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80110. this._physicsPlugin.setTimeStep(newTimeStep);
  80111. };
  80112. /**
  80113. * Get the time step of the physics engine.
  80114. */
  80115. PhysicsEngine.prototype.getTimeStep = function () {
  80116. return this._physicsPlugin.getTimeStep();
  80117. };
  80118. PhysicsEngine.prototype.dispose = function () {
  80119. this._impostors.forEach(function (impostor) {
  80120. impostor.dispose();
  80121. });
  80122. this._physicsPlugin.dispose();
  80123. };
  80124. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80125. return this._physicsPlugin.name;
  80126. };
  80127. /**
  80128. * Adding a new impostor for the impostor tracking.
  80129. * This will be done by the impostor itself.
  80130. * @param {PhysicsImpostor} impostor the impostor to add
  80131. */
  80132. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80133. impostor.uniqueId = this._impostors.push(impostor);
  80134. //if no parent, generate the body
  80135. if (!impostor.parent) {
  80136. this._physicsPlugin.generatePhysicsBody(impostor);
  80137. }
  80138. };
  80139. /**
  80140. * Remove an impostor from the engine.
  80141. * This impostor and its mesh will not longer be updated by the physics engine.
  80142. * @param {PhysicsImpostor} impostor the impostor to remove
  80143. */
  80144. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80145. var index = this._impostors.indexOf(impostor);
  80146. if (index > -1) {
  80147. var removed = this._impostors.splice(index, 1);
  80148. //Is it needed?
  80149. if (removed.length) {
  80150. //this will also remove it from the world.
  80151. removed[0].physicsBody = null;
  80152. }
  80153. }
  80154. };
  80155. /**
  80156. * Add a joint to the physics engine
  80157. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80158. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80159. * @param {PhysicsJoint} the joint that will connect both impostors.
  80160. */
  80161. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80162. var impostorJoint = {
  80163. mainImpostor: mainImpostor,
  80164. connectedImpostor: connectedImpostor,
  80165. joint: joint
  80166. };
  80167. joint.physicsPlugin = this._physicsPlugin;
  80168. this._joints.push(impostorJoint);
  80169. this._physicsPlugin.generateJoint(impostorJoint);
  80170. };
  80171. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80172. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80173. return (impostorJoint.connectedImpostor === connectedImpostor
  80174. && impostorJoint.joint === joint
  80175. && impostorJoint.mainImpostor === mainImpostor);
  80176. });
  80177. if (matchingJoints.length) {
  80178. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80179. //TODO remove it from the list as well
  80180. }
  80181. };
  80182. /**
  80183. * Called by the scene. no need to call it.
  80184. */
  80185. PhysicsEngine.prototype._step = function (delta) {
  80186. var _this = this;
  80187. //check if any mesh has no body / requires an update
  80188. this._impostors.forEach(function (impostor) {
  80189. if (impostor.isBodyInitRequired()) {
  80190. _this._physicsPlugin.generatePhysicsBody(impostor);
  80191. }
  80192. });
  80193. if (delta > 0.1) {
  80194. delta = 0.1;
  80195. }
  80196. else if (delta <= 0) {
  80197. delta = 1.0 / 60.0;
  80198. }
  80199. this._physicsPlugin.executeStep(delta, this._impostors);
  80200. };
  80201. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  80202. return this._physicsPlugin;
  80203. };
  80204. PhysicsEngine.prototype.getImpostors = function () {
  80205. return this._impostors;
  80206. };
  80207. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  80208. for (var i = 0; i < this._impostors.length; ++i) {
  80209. if (this._impostors[i].object === object) {
  80210. return this._impostors[i];
  80211. }
  80212. }
  80213. return null;
  80214. };
  80215. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  80216. for (var i = 0; i < this._impostors.length; ++i) {
  80217. if (this._impostors[i].physicsBody === body) {
  80218. return this._impostors[i];
  80219. }
  80220. }
  80221. return null;
  80222. };
  80223. // Statics
  80224. PhysicsEngine.Epsilon = 0.001;
  80225. return PhysicsEngine;
  80226. }());
  80227. BABYLON.PhysicsEngine = PhysicsEngine;
  80228. })(BABYLON || (BABYLON = {}));
  80229. //# sourceMappingURL=babylon.physicsEngine.js.map
  80230. "use strict";
  80231. var BABYLON;
  80232. (function (BABYLON) {
  80233. var PhysicsHelper = /** @class */ (function () {
  80234. function PhysicsHelper(scene) {
  80235. this._scene = scene;
  80236. this._physicsEngine = this._scene.getPhysicsEngine();
  80237. if (!this._physicsEngine) {
  80238. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  80239. }
  80240. }
  80241. /**
  80242. * @param {Vector3} origin the origin of the explosion
  80243. * @param {number} radius the explosion radius
  80244. * @param {number} strength the explosion strength
  80245. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80246. */
  80247. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  80248. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80249. if (!this._physicsEngine) {
  80250. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  80251. return null;
  80252. }
  80253. var impostors = this._physicsEngine.getImpostors();
  80254. if (impostors.length === 0) {
  80255. return null;
  80256. }
  80257. var event = new PhysicsRadialExplosionEvent(this._scene);
  80258. impostors.forEach(function (impostor) {
  80259. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80260. if (!impostorForceAndContactPoint) {
  80261. return;
  80262. }
  80263. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80264. });
  80265. event.dispose(false);
  80266. return event;
  80267. };
  80268. /**
  80269. * @param {Vector3} origin the origin of the explosion
  80270. * @param {number} radius the explosion radius
  80271. * @param {number} strength the explosion strength
  80272. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80273. */
  80274. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  80275. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80276. if (!this._physicsEngine) {
  80277. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80278. return null;
  80279. }
  80280. var impostors = this._physicsEngine.getImpostors();
  80281. if (impostors.length === 0) {
  80282. return null;
  80283. }
  80284. var event = new PhysicsRadialExplosionEvent(this._scene);
  80285. impostors.forEach(function (impostor) {
  80286. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80287. if (!impostorForceAndContactPoint) {
  80288. return;
  80289. }
  80290. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80291. });
  80292. event.dispose(false);
  80293. return event;
  80294. };
  80295. /**
  80296. * @param {Vector3} origin the origin of the explosion
  80297. * @param {number} radius the explosion radius
  80298. * @param {number} strength the explosion strength
  80299. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80300. */
  80301. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  80302. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80303. if (!this._physicsEngine) {
  80304. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80305. return null;
  80306. }
  80307. var impostors = this._physicsEngine.getImpostors();
  80308. if (impostors.length === 0) {
  80309. return null;
  80310. }
  80311. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  80312. event.dispose(false);
  80313. return event;
  80314. };
  80315. /**
  80316. * @param {Vector3} origin the origin of the updraft
  80317. * @param {number} radius the radius of the updraft
  80318. * @param {number} strength the strength of the updraft
  80319. * @param {number} height the height of the updraft
  80320. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  80321. */
  80322. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  80323. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  80324. if (!this._physicsEngine) {
  80325. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80326. return null;
  80327. }
  80328. if (this._physicsEngine.getImpostors().length === 0) {
  80329. return null;
  80330. }
  80331. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  80332. event.dispose(false);
  80333. return event;
  80334. };
  80335. /**
  80336. * @param {Vector3} origin the of the vortex
  80337. * @param {number} radius the radius of the vortex
  80338. * @param {number} strength the strength of the vortex
  80339. * @param {number} height the height of the vortex
  80340. */
  80341. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  80342. if (!this._physicsEngine) {
  80343. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80344. return null;
  80345. }
  80346. if (this._physicsEngine.getImpostors().length === 0) {
  80347. return null;
  80348. }
  80349. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  80350. event.dispose(false);
  80351. return event;
  80352. };
  80353. return PhysicsHelper;
  80354. }());
  80355. BABYLON.PhysicsHelper = PhysicsHelper;
  80356. /***** Radial explosion *****/
  80357. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  80358. function PhysicsRadialExplosionEvent(scene) {
  80359. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  80360. this._rays = [];
  80361. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  80362. this._scene = scene;
  80363. }
  80364. /**
  80365. * Returns the data related to the radial explosion event (sphere & rays).
  80366. * @returns {PhysicsRadialExplosionEventData}
  80367. */
  80368. PhysicsRadialExplosionEvent.prototype.getData = function () {
  80369. this._dataFetched = true;
  80370. return {
  80371. sphere: this._sphere,
  80372. rays: this._rays,
  80373. };
  80374. };
  80375. /**
  80376. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  80377. * @param impostor
  80378. * @param {Vector3} origin the origin of the explosion
  80379. * @param {number} radius the explosion radius
  80380. * @param {number} strength the explosion strength
  80381. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  80382. * @returns {Nullable<PhysicsForceAndContactPoint>}
  80383. */
  80384. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  80385. if (impostor.mass === 0) {
  80386. return null;
  80387. }
  80388. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  80389. return null;
  80390. }
  80391. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80392. return null;
  80393. }
  80394. var impostorObjectCenter = impostor.getObjectCenter();
  80395. var direction = impostorObjectCenter.subtract(origin);
  80396. var ray = new BABYLON.Ray(origin, direction, radius);
  80397. this._rays.push(ray);
  80398. var hit = ray.intersectsMesh(impostor.object);
  80399. var contactPoint = hit.pickedPoint;
  80400. if (!contactPoint) {
  80401. return null;
  80402. }
  80403. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  80404. if (distanceFromOrigin > radius) {
  80405. return null;
  80406. }
  80407. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  80408. ? strength
  80409. : strength * (1 - (distanceFromOrigin / radius));
  80410. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80411. return { force: force, contactPoint: contactPoint };
  80412. };
  80413. /**
  80414. * Disposes the sphere.
  80415. * @param {bolean} force
  80416. */
  80417. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  80418. var _this = this;
  80419. if (force === void 0) { force = true; }
  80420. if (force) {
  80421. this._sphere.dispose();
  80422. }
  80423. else {
  80424. setTimeout(function () {
  80425. if (!_this._dataFetched) {
  80426. _this._sphere.dispose();
  80427. }
  80428. }, 0);
  80429. }
  80430. };
  80431. /*** Helpers ***/
  80432. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  80433. if (!this._sphere) {
  80434. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  80435. this._sphere.isVisible = false;
  80436. }
  80437. };
  80438. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  80439. var impostorObject = impostor.object;
  80440. this._prepareSphere();
  80441. this._sphere.position = origin;
  80442. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  80443. this._sphere._updateBoundingInfo();
  80444. this._sphere.computeWorldMatrix(true);
  80445. return this._sphere.intersectsMesh(impostorObject, true);
  80446. };
  80447. return PhysicsRadialExplosionEvent;
  80448. }());
  80449. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  80450. /***** Gravitational Field *****/
  80451. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  80452. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  80453. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80454. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80455. this._physicsHelper = physicsHelper;
  80456. this._scene = scene;
  80457. this._origin = origin;
  80458. this._radius = radius;
  80459. this._strength = strength;
  80460. this._falloff = falloff;
  80461. this._tickCallback = this._tick.bind(this);
  80462. }
  80463. /**
  80464. * Returns the data related to the gravitational field event (sphere).
  80465. * @returns {PhysicsGravitationalFieldEventData}
  80466. */
  80467. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  80468. this._dataFetched = true;
  80469. return {
  80470. sphere: this._sphere,
  80471. };
  80472. };
  80473. /**
  80474. * Enables the gravitational field.
  80475. */
  80476. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  80477. this._tickCallback.call(this);
  80478. this._scene.registerBeforeRender(this._tickCallback);
  80479. };
  80480. /**
  80481. * Disables the gravitational field.
  80482. */
  80483. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  80484. this._scene.unregisterBeforeRender(this._tickCallback);
  80485. };
  80486. /**
  80487. * Disposes the sphere.
  80488. * @param {bolean} force
  80489. */
  80490. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  80491. var _this = this;
  80492. if (force === void 0) { force = true; }
  80493. if (force) {
  80494. this._sphere.dispose();
  80495. }
  80496. else {
  80497. setTimeout(function () {
  80498. if (!_this._dataFetched) {
  80499. _this._sphere.dispose();
  80500. }
  80501. }, 0);
  80502. }
  80503. };
  80504. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  80505. // Since the params won't change, we fetch the event only once
  80506. if (this._sphere) {
  80507. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80508. }
  80509. else {
  80510. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80511. if (radialExplosionEvent) {
  80512. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  80513. }
  80514. }
  80515. };
  80516. return PhysicsGravitationalFieldEvent;
  80517. }());
  80518. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  80519. /***** Updraft *****/
  80520. var PhysicsUpdraftEvent = /** @class */ (function () {
  80521. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  80522. this._scene = _scene;
  80523. this._origin = _origin;
  80524. this._radius = _radius;
  80525. this._strength = _strength;
  80526. this._height = _height;
  80527. this._updraftMode = _updraftMode;
  80528. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80529. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  80530. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80531. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80532. this._physicsEngine = this._scene.getPhysicsEngine();
  80533. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80534. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80535. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80536. this._originDirection = this._origin.subtract(this._originTop).normalize();
  80537. }
  80538. this._tickCallback = this._tick.bind(this);
  80539. }
  80540. /**
  80541. * Returns the data related to the updraft event (cylinder).
  80542. * @returns {PhysicsUpdraftEventData}
  80543. */
  80544. PhysicsUpdraftEvent.prototype.getData = function () {
  80545. this._dataFetched = true;
  80546. return {
  80547. cylinder: this._cylinder,
  80548. };
  80549. };
  80550. /**
  80551. * Enables the updraft.
  80552. */
  80553. PhysicsUpdraftEvent.prototype.enable = function () {
  80554. this._tickCallback.call(this);
  80555. this._scene.registerBeforeRender(this._tickCallback);
  80556. };
  80557. /**
  80558. * Disables the cortex.
  80559. */
  80560. PhysicsUpdraftEvent.prototype.disable = function () {
  80561. this._scene.unregisterBeforeRender(this._tickCallback);
  80562. };
  80563. /**
  80564. * Disposes the sphere.
  80565. * @param {bolean} force
  80566. */
  80567. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  80568. var _this = this;
  80569. if (force === void 0) { force = true; }
  80570. if (force) {
  80571. this._cylinder.dispose();
  80572. }
  80573. else {
  80574. setTimeout(function () {
  80575. if (!_this._dataFetched) {
  80576. _this._cylinder.dispose();
  80577. }
  80578. }, 0);
  80579. }
  80580. };
  80581. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  80582. if (impostor.mass === 0) {
  80583. return null;
  80584. }
  80585. if (!this._intersectsWithCylinder(impostor)) {
  80586. return null;
  80587. }
  80588. var impostorObjectCenter = impostor.getObjectCenter();
  80589. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80590. var direction = this._originDirection;
  80591. }
  80592. else {
  80593. var direction = impostorObjectCenter.subtract(this._originTop);
  80594. }
  80595. var multiplier = this._strength * -1;
  80596. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80597. return { force: force, contactPoint: impostorObjectCenter };
  80598. };
  80599. PhysicsUpdraftEvent.prototype._tick = function () {
  80600. var _this = this;
  80601. this._physicsEngine.getImpostors().forEach(function (impostor) {
  80602. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  80603. if (!impostorForceAndContactPoint) {
  80604. return;
  80605. }
  80606. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80607. });
  80608. };
  80609. /*** Helpers ***/
  80610. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  80611. if (!this._cylinder) {
  80612. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  80613. height: this._height,
  80614. diameter: this._radius * 2,
  80615. }, this._scene);
  80616. this._cylinder.isVisible = false;
  80617. }
  80618. };
  80619. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  80620. var impostorObject = impostor.object;
  80621. this._prepareCylinder();
  80622. this._cylinder.position = this._cylinderPosition;
  80623. return this._cylinder.intersectsMesh(impostorObject, true);
  80624. };
  80625. return PhysicsUpdraftEvent;
  80626. }());
  80627. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  80628. /***** Vortex *****/
  80629. var PhysicsVortexEvent = /** @class */ (function () {
  80630. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  80631. this._scene = _scene;
  80632. this._origin = _origin;
  80633. this._radius = _radius;
  80634. this._strength = _strength;
  80635. this._height = _height;
  80636. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80637. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  80638. this._updraftMultiplier = 0.02;
  80639. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80640. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80641. this._physicsEngine = this._scene.getPhysicsEngine();
  80642. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80643. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80644. this._tickCallback = this._tick.bind(this);
  80645. }
  80646. /**
  80647. * Returns the data related to the vortex event (cylinder).
  80648. * @returns {PhysicsVortexEventData}
  80649. */
  80650. PhysicsVortexEvent.prototype.getData = function () {
  80651. this._dataFetched = true;
  80652. return {
  80653. cylinder: this._cylinder,
  80654. };
  80655. };
  80656. /**
  80657. * Enables the vortex.
  80658. */
  80659. PhysicsVortexEvent.prototype.enable = function () {
  80660. this._tickCallback.call(this);
  80661. this._scene.registerBeforeRender(this._tickCallback);
  80662. };
  80663. /**
  80664. * Disables the cortex.
  80665. */
  80666. PhysicsVortexEvent.prototype.disable = function () {
  80667. this._scene.unregisterBeforeRender(this._tickCallback);
  80668. };
  80669. /**
  80670. * Disposes the sphere.
  80671. * @param {bolean} force
  80672. */
  80673. PhysicsVortexEvent.prototype.dispose = function (force) {
  80674. var _this = this;
  80675. if (force === void 0) { force = true; }
  80676. if (force) {
  80677. this._cylinder.dispose();
  80678. }
  80679. else {
  80680. setTimeout(function () {
  80681. if (!_this._dataFetched) {
  80682. _this._cylinder.dispose();
  80683. }
  80684. }, 0);
  80685. }
  80686. };
  80687. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  80688. if (impostor.mass === 0) {
  80689. return null;
  80690. }
  80691. if (!this._intersectsWithCylinder(impostor)) {
  80692. return null;
  80693. }
  80694. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80695. return null;
  80696. }
  80697. var impostorObjectCenter = impostor.getObjectCenter();
  80698. 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)
  80699. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  80700. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  80701. var hit = ray.intersectsMesh(impostor.object);
  80702. var contactPoint = hit.pickedPoint;
  80703. if (!contactPoint) {
  80704. return null;
  80705. }
  80706. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  80707. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  80708. var directionToOrigin = contactPoint.normalize();
  80709. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  80710. directionToOrigin = directionToOrigin.negate();
  80711. }
  80712. // TODO: find a more physically based solution
  80713. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  80714. var forceX = directionToOrigin.x * this._strength / 8;
  80715. var forceY = directionToOrigin.y * this._updraftMultiplier;
  80716. var forceZ = directionToOrigin.z * this._strength / 8;
  80717. }
  80718. else {
  80719. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  80720. var forceY = this._originTop.y * this._updraftMultiplier;
  80721. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  80722. }
  80723. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  80724. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  80725. return { force: force, contactPoint: impostorObjectCenter };
  80726. };
  80727. PhysicsVortexEvent.prototype._tick = function () {
  80728. var _this = this;
  80729. this._physicsEngine.getImpostors().forEach(function (impostor) {
  80730. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  80731. if (!impostorForceAndContactPoint) {
  80732. return;
  80733. }
  80734. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80735. });
  80736. };
  80737. /*** Helpers ***/
  80738. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  80739. if (!this._cylinder) {
  80740. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  80741. height: this._height,
  80742. diameter: this._radius * 2,
  80743. }, this._scene);
  80744. this._cylinder.isVisible = false;
  80745. }
  80746. };
  80747. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  80748. var impostorObject = impostor.object;
  80749. this._prepareCylinder();
  80750. this._cylinder.position = this._cylinderPosition;
  80751. return this._cylinder.intersectsMesh(impostorObject, true);
  80752. };
  80753. return PhysicsVortexEvent;
  80754. }());
  80755. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  80756. /***** Enums *****/
  80757. /**
  80758. * The strenght of the force in correspondence to the distance of the affected object
  80759. */
  80760. var PhysicsRadialImpulseFalloff;
  80761. (function (PhysicsRadialImpulseFalloff) {
  80762. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  80763. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  80764. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  80765. /**
  80766. * The strenght of the force in correspondence to the distance of the affected object
  80767. */
  80768. var PhysicsUpdraftMode;
  80769. (function (PhysicsUpdraftMode) {
  80770. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  80771. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  80772. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  80773. })(BABYLON || (BABYLON = {}));
  80774. //# sourceMappingURL=babylon.physicsHelper.js.map
  80775. "use strict";
  80776. var BABYLON;
  80777. (function (BABYLON) {
  80778. var CannonJSPlugin = /** @class */ (function () {
  80779. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  80780. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  80781. if (iterations === void 0) { iterations = 10; }
  80782. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  80783. this.name = "CannonJSPlugin";
  80784. this._physicsMaterials = new Array();
  80785. this._fixedTimeStep = 1 / 60;
  80786. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  80787. this.BJSCANNON = CANNON;
  80788. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  80789. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  80790. this._tmpPosition = BABYLON.Vector3.Zero();
  80791. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  80792. this._tmpUnityRotation = new BABYLON.Quaternion();
  80793. if (!this.isSupported()) {
  80794. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  80795. return;
  80796. }
  80797. this._extendNamespace();
  80798. this.world = new this.BJSCANNON.World();
  80799. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  80800. this.world.solver.iterations = iterations;
  80801. }
  80802. CannonJSPlugin.prototype.setGravity = function (gravity) {
  80803. this.world.gravity.copy(gravity);
  80804. };
  80805. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  80806. this._fixedTimeStep = timeStep;
  80807. };
  80808. CannonJSPlugin.prototype.getTimeStep = function () {
  80809. return this._fixedTimeStep;
  80810. };
  80811. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  80812. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  80813. };
  80814. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  80815. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  80816. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  80817. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  80818. };
  80819. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  80820. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  80821. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  80822. impostor.physicsBody.applyForce(impulse, worldPoint);
  80823. };
  80824. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  80825. //parent-child relationship. Does this impostor has a parent impostor?
  80826. if (impostor.parent) {
  80827. if (impostor.physicsBody) {
  80828. this.removePhysicsBody(impostor);
  80829. //TODO is that needed?
  80830. impostor.forceUpdate();
  80831. }
  80832. return;
  80833. }
  80834. //should a new body be created for this impostor?
  80835. if (impostor.isBodyInitRequired()) {
  80836. var shape = this._createShape(impostor);
  80837. //unregister events, if body is being changed
  80838. var oldBody = impostor.physicsBody;
  80839. if (oldBody) {
  80840. this.removePhysicsBody(impostor);
  80841. }
  80842. //create the body and material
  80843. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  80844. var bodyCreationObject = {
  80845. mass: impostor.getParam("mass"),
  80846. material: material
  80847. };
  80848. // A simple extend, in case native options were used.
  80849. var nativeOptions = impostor.getParam("nativeOptions");
  80850. for (var key in nativeOptions) {
  80851. if (nativeOptions.hasOwnProperty(key)) {
  80852. bodyCreationObject[key] = nativeOptions[key];
  80853. }
  80854. }
  80855. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  80856. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  80857. this.world.addEventListener("preStep", impostor.beforeStep);
  80858. this.world.addEventListener("postStep", impostor.afterStep);
  80859. impostor.physicsBody.addShape(shape);
  80860. this.world.add(impostor.physicsBody);
  80861. //try to keep the body moving in the right direction by taking old properties.
  80862. //Should be tested!
  80863. if (oldBody) {
  80864. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  80865. impostor.physicsBody[param].copy(oldBody[param]);
  80866. });
  80867. }
  80868. this._processChildMeshes(impostor);
  80869. }
  80870. //now update the body's transformation
  80871. this._updatePhysicsBodyTransformation(impostor);
  80872. };
  80873. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  80874. var _this = this;
  80875. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  80876. var currentRotation = mainImpostor.object.rotationQuaternion;
  80877. if (meshChildren.length) {
  80878. var processMesh = function (localPosition, mesh) {
  80879. if (!currentRotation || !mesh.rotationQuaternion) {
  80880. return;
  80881. }
  80882. var childImpostor = mesh.getPhysicsImpostor();
  80883. if (childImpostor) {
  80884. var parent = childImpostor.parent;
  80885. if (parent !== mainImpostor) {
  80886. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  80887. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  80888. if (childImpostor.physicsBody) {
  80889. _this.removePhysicsBody(childImpostor);
  80890. childImpostor.physicsBody = null;
  80891. }
  80892. childImpostor.parent = mainImpostor;
  80893. childImpostor.resetUpdateFlags();
  80894. 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));
  80895. //Add the mass of the children.
  80896. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  80897. }
  80898. }
  80899. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  80900. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  80901. };
  80902. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  80903. }
  80904. };
  80905. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  80906. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  80907. this.world.removeEventListener("preStep", impostor.beforeStep);
  80908. this.world.removeEventListener("postStep", impostor.afterStep);
  80909. this.world.remove(impostor.physicsBody);
  80910. };
  80911. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  80912. var mainBody = impostorJoint.mainImpostor.physicsBody;
  80913. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  80914. if (!mainBody || !connectedBody) {
  80915. return;
  80916. }
  80917. var constraint;
  80918. var jointData = impostorJoint.joint.jointData;
  80919. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  80920. var constraintData = {
  80921. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  80922. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  80923. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  80924. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  80925. maxForce: jointData.nativeParams.maxForce,
  80926. collideConnected: !!jointData.collision
  80927. };
  80928. switch (impostorJoint.joint.type) {
  80929. case BABYLON.PhysicsJoint.HingeJoint:
  80930. case BABYLON.PhysicsJoint.Hinge2Joint:
  80931. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  80932. break;
  80933. case BABYLON.PhysicsJoint.DistanceJoint:
  80934. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  80935. break;
  80936. case BABYLON.PhysicsJoint.SpringJoint:
  80937. var springData = jointData;
  80938. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  80939. restLength: springData.length,
  80940. stiffness: springData.stiffness,
  80941. damping: springData.damping,
  80942. localAnchorA: constraintData.pivotA,
  80943. localAnchorB: constraintData.pivotB
  80944. });
  80945. break;
  80946. case BABYLON.PhysicsJoint.LockJoint:
  80947. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  80948. break;
  80949. case BABYLON.PhysicsJoint.PointToPointJoint:
  80950. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  80951. default:
  80952. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  80953. break;
  80954. }
  80955. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  80956. constraint.collideConnected = !!jointData.collision;
  80957. impostorJoint.joint.physicsJoint = constraint;
  80958. //don't add spring as constraint, as it is not one.
  80959. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  80960. this.world.addConstraint(constraint);
  80961. }
  80962. else {
  80963. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  80964. constraint.applyForce();
  80965. });
  80966. }
  80967. };
  80968. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  80969. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  80970. };
  80971. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  80972. var index;
  80973. var mat;
  80974. for (index = 0; index < this._physicsMaterials.length; index++) {
  80975. mat = this._physicsMaterials[index];
  80976. if (mat.friction === friction && mat.restitution === restitution) {
  80977. return mat;
  80978. }
  80979. }
  80980. var currentMat = new this.BJSCANNON.Material(name);
  80981. currentMat.friction = friction;
  80982. currentMat.restitution = restitution;
  80983. this._physicsMaterials.push(currentMat);
  80984. return currentMat;
  80985. };
  80986. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  80987. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  80988. };
  80989. CannonJSPlugin.prototype._createShape = function (impostor) {
  80990. var object = impostor.object;
  80991. var returnValue;
  80992. var extendSize = impostor.getObjectExtendSize();
  80993. switch (impostor.type) {
  80994. case BABYLON.PhysicsImpostor.SphereImpostor:
  80995. var radiusX = extendSize.x;
  80996. var radiusY = extendSize.y;
  80997. var radiusZ = extendSize.z;
  80998. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  80999. break;
  81000. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  81001. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81002. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  81003. break;
  81004. case BABYLON.PhysicsImpostor.BoxImpostor:
  81005. var box = extendSize.scale(0.5);
  81006. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  81007. break;
  81008. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81009. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  81010. returnValue = new this.BJSCANNON.Plane();
  81011. break;
  81012. case BABYLON.PhysicsImpostor.MeshImpostor:
  81013. // should transform the vertex data to world coordinates!!
  81014. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  81015. var rawFaces = object.getIndices ? object.getIndices() : [];
  81016. if (!rawVerts)
  81017. return;
  81018. // get only scale! so the object could transform correctly.
  81019. var oldPosition = object.position.clone();
  81020. var oldRotation = object.rotation && object.rotation.clone();
  81021. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  81022. object.position.copyFromFloats(0, 0, 0);
  81023. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81024. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81025. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81026. var transform = object.computeWorldMatrix(true);
  81027. // convert rawVerts to object space
  81028. var temp = new Array();
  81029. var index;
  81030. for (index = 0; index < rawVerts.length; index += 3) {
  81031. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  81032. }
  81033. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  81034. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  81035. //now set back the transformation!
  81036. object.position.copyFrom(oldPosition);
  81037. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  81038. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  81039. break;
  81040. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  81041. var oldPosition2 = object.position.clone();
  81042. var oldRotation2 = object.rotation && object.rotation.clone();
  81043. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  81044. object.position.copyFromFloats(0, 0, 0);
  81045. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81046. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81047. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81048. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  81049. returnValue = this._createHeightmap(object);
  81050. object.position.copyFrom(oldPosition2);
  81051. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  81052. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  81053. object.computeWorldMatrix(true);
  81054. break;
  81055. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81056. returnValue = new this.BJSCANNON.Particle();
  81057. break;
  81058. }
  81059. return returnValue;
  81060. };
  81061. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  81062. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81063. var transform = object.computeWorldMatrix(true);
  81064. // convert rawVerts to object space
  81065. var temp = new Array();
  81066. var index;
  81067. for (index = 0; index < pos.length; index += 3) {
  81068. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  81069. }
  81070. pos = temp;
  81071. var matrix = new Array();
  81072. //For now pointDepth will not be used and will be automatically calculated.
  81073. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  81074. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  81075. var boundingInfo = object.getBoundingInfo();
  81076. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  81077. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  81078. var elementSize = dim * 2 / arraySize;
  81079. for (var i = 0; i < pos.length; i = i + 3) {
  81080. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  81081. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  81082. var y = -pos[i + 2] + minY;
  81083. if (!matrix[x]) {
  81084. matrix[x] = [];
  81085. }
  81086. if (!matrix[x][z]) {
  81087. matrix[x][z] = y;
  81088. }
  81089. matrix[x][z] = Math.max(y, matrix[x][z]);
  81090. }
  81091. for (var x = 0; x <= arraySize; ++x) {
  81092. if (!matrix[x]) {
  81093. var loc = 1;
  81094. while (!matrix[(x + loc) % arraySize]) {
  81095. loc++;
  81096. }
  81097. matrix[x] = matrix[(x + loc) % arraySize].slice();
  81098. //console.log("missing x", x);
  81099. }
  81100. for (var z = 0; z <= arraySize; ++z) {
  81101. if (!matrix[x][z]) {
  81102. var loc = 1;
  81103. var newValue;
  81104. while (newValue === undefined) {
  81105. newValue = matrix[x][(z + loc++) % arraySize];
  81106. }
  81107. matrix[x][z] = newValue;
  81108. }
  81109. }
  81110. }
  81111. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81112. elementSize: elementSize
  81113. });
  81114. //For future reference, needed for body transformation
  81115. shape.minY = minY;
  81116. return shape;
  81117. };
  81118. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81119. var object = impostor.object;
  81120. //make sure it is updated...
  81121. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81122. // The delta between the mesh position and the mesh bounding box center
  81123. var bInfo = object.getBoundingInfo();
  81124. if (!bInfo)
  81125. return;
  81126. var center = impostor.getObjectCenter();
  81127. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81128. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81129. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81130. this._tmpPosition.copyFrom(center);
  81131. var quaternion = object.rotationQuaternion;
  81132. if (!quaternion) {
  81133. return;
  81134. }
  81135. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81136. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81137. //-90 DEG in X, precalculated
  81138. quaternion = quaternion.multiply(this._minus90X);
  81139. //Invert! (Precalculated, 90 deg in X)
  81140. //No need to clone. this will never change.
  81141. impostor.setDeltaRotation(this._plus90X);
  81142. }
  81143. //If it is a heightfield, if should be centered.
  81144. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81145. var mesh = object;
  81146. var boundingInfo = mesh.getBoundingInfo();
  81147. //calculate the correct body position:
  81148. var rotationQuaternion = mesh.rotationQuaternion;
  81149. mesh.rotationQuaternion = this._tmpUnityRotation;
  81150. mesh.computeWorldMatrix(true);
  81151. //get original center with no rotation
  81152. var c = center.clone();
  81153. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81154. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81155. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81156. mesh.setPreTransformMatrix(p);
  81157. mesh.computeWorldMatrix(true);
  81158. //calculate the translation
  81159. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81160. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81161. //add it inverted to the delta
  81162. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81163. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81164. //rotation is back
  81165. mesh.rotationQuaternion = rotationQuaternion;
  81166. mesh.setPreTransformMatrix(oldPivot);
  81167. mesh.computeWorldMatrix(true);
  81168. }
  81169. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81170. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81171. //this._tmpPosition.copyFrom(object.position);
  81172. }
  81173. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81174. //Now update the impostor object
  81175. impostor.physicsBody.position.copy(this._tmpPosition);
  81176. impostor.physicsBody.quaternion.copy(quaternion);
  81177. };
  81178. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81179. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81180. if (impostor.object.rotationQuaternion) {
  81181. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81182. }
  81183. };
  81184. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81185. impostor.physicsBody.position.copy(newPosition);
  81186. impostor.physicsBody.quaternion.copy(newRotation);
  81187. };
  81188. CannonJSPlugin.prototype.isSupported = function () {
  81189. return this.BJSCANNON !== undefined;
  81190. };
  81191. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81192. impostor.physicsBody.velocity.copy(velocity);
  81193. };
  81194. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81195. impostor.physicsBody.angularVelocity.copy(velocity);
  81196. };
  81197. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81198. var v = impostor.physicsBody.velocity;
  81199. if (!v) {
  81200. return null;
  81201. }
  81202. return new BABYLON.Vector3(v.x, v.y, v.z);
  81203. };
  81204. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81205. var v = impostor.physicsBody.angularVelocity;
  81206. if (!v) {
  81207. return null;
  81208. }
  81209. return new BABYLON.Vector3(v.x, v.y, v.z);
  81210. };
  81211. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81212. impostor.physicsBody.mass = mass;
  81213. impostor.physicsBody.updateMassProperties();
  81214. };
  81215. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  81216. return impostor.physicsBody.mass;
  81217. };
  81218. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  81219. return impostor.physicsBody.material.friction;
  81220. };
  81221. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81222. impostor.physicsBody.material.friction = friction;
  81223. };
  81224. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81225. return impostor.physicsBody.material.restitution;
  81226. };
  81227. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81228. impostor.physicsBody.material.restitution = restitution;
  81229. };
  81230. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  81231. impostor.physicsBody.sleep();
  81232. };
  81233. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  81234. impostor.physicsBody.wakeUp();
  81235. };
  81236. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81237. joint.physicsJoint.distance = maxDistance;
  81238. };
  81239. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81240. // if (!motorIndex) {
  81241. // joint.physicsJoint.enableMotor();
  81242. // }
  81243. // }
  81244. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81245. // if (!motorIndex) {
  81246. // joint.physicsJoint.disableMotor();
  81247. // }
  81248. // }
  81249. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81250. if (!motorIndex) {
  81251. joint.physicsJoint.enableMotor();
  81252. joint.physicsJoint.setMotorSpeed(speed);
  81253. if (maxForce) {
  81254. this.setLimit(joint, maxForce);
  81255. }
  81256. }
  81257. };
  81258. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  81259. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  81260. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  81261. };
  81262. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81263. var body = impostor.physicsBody;
  81264. mesh.position.x = body.position.x;
  81265. mesh.position.y = body.position.y;
  81266. mesh.position.z = body.position.z;
  81267. if (mesh.rotationQuaternion) {
  81268. mesh.rotationQuaternion.x = body.quaternion.x;
  81269. mesh.rotationQuaternion.y = body.quaternion.y;
  81270. mesh.rotationQuaternion.z = body.quaternion.z;
  81271. mesh.rotationQuaternion.w = body.quaternion.w;
  81272. }
  81273. };
  81274. CannonJSPlugin.prototype.getRadius = function (impostor) {
  81275. var shape = impostor.physicsBody.shapes[0];
  81276. return shape.boundingSphereRadius;
  81277. };
  81278. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81279. var shape = impostor.physicsBody.shapes[0];
  81280. result.x = shape.halfExtents.x * 2;
  81281. result.y = shape.halfExtents.y * 2;
  81282. result.z = shape.halfExtents.z * 2;
  81283. };
  81284. CannonJSPlugin.prototype.dispose = function () {
  81285. };
  81286. CannonJSPlugin.prototype._extendNamespace = function () {
  81287. //this will force cannon to execute at least one step when using interpolation
  81288. var step_tmp1 = new this.BJSCANNON.Vec3();
  81289. var Engine = this.BJSCANNON;
  81290. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  81291. maxSubSteps = maxSubSteps || 10;
  81292. timeSinceLastCalled = timeSinceLastCalled || 0;
  81293. if (timeSinceLastCalled === 0) {
  81294. this.internalStep(dt);
  81295. this.time += dt;
  81296. }
  81297. else {
  81298. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  81299. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  81300. var t0 = performance.now();
  81301. for (var i = 0; i !== internalSteps; i++) {
  81302. this.internalStep(dt);
  81303. if (performance.now() - t0 > dt * 1000) {
  81304. break;
  81305. }
  81306. }
  81307. this.time += timeSinceLastCalled;
  81308. var h = this.time % dt;
  81309. var h_div_dt = h / dt;
  81310. var interpvelo = step_tmp1;
  81311. var bodies = this.bodies;
  81312. for (var j = 0; j !== bodies.length; j++) {
  81313. var b = bodies[j];
  81314. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  81315. b.position.vsub(b.previousPosition, interpvelo);
  81316. interpvelo.scale(h_div_dt, interpvelo);
  81317. b.position.vadd(interpvelo, b.interpolatedPosition);
  81318. }
  81319. else {
  81320. b.interpolatedPosition.copy(b.position);
  81321. b.interpolatedQuaternion.copy(b.quaternion);
  81322. }
  81323. }
  81324. }
  81325. };
  81326. };
  81327. return CannonJSPlugin;
  81328. }());
  81329. BABYLON.CannonJSPlugin = CannonJSPlugin;
  81330. })(BABYLON || (BABYLON = {}));
  81331. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  81332. "use strict";
  81333. var BABYLON;
  81334. (function (BABYLON) {
  81335. var OimoJSPlugin = /** @class */ (function () {
  81336. function OimoJSPlugin(iterations) {
  81337. this.name = "OimoJSPlugin";
  81338. this._tmpImpostorsArray = [];
  81339. this._tmpPositionVector = BABYLON.Vector3.Zero();
  81340. this.BJSOIMO = OIMO;
  81341. this.world = new this.BJSOIMO.World({
  81342. iterations: iterations
  81343. });
  81344. this.world.clear();
  81345. }
  81346. OimoJSPlugin.prototype.setGravity = function (gravity) {
  81347. this.world.gravity.copy(gravity);
  81348. };
  81349. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  81350. this.world.timeStep = timeStep;
  81351. };
  81352. OimoJSPlugin.prototype.getTimeStep = function () {
  81353. return this.world.timeStep;
  81354. };
  81355. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  81356. var _this = this;
  81357. impostors.forEach(function (impostor) {
  81358. impostor.beforeStep();
  81359. });
  81360. this.world.step();
  81361. impostors.forEach(function (impostor) {
  81362. impostor.afterStep();
  81363. //update the ordered impostors array
  81364. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  81365. });
  81366. //check for collisions
  81367. var contact = this.world.contacts;
  81368. while (contact !== null) {
  81369. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  81370. contact = contact.next;
  81371. continue;
  81372. }
  81373. //is this body colliding with any other? get the impostor
  81374. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  81375. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  81376. if (!mainImpostor || !collidingImpostor) {
  81377. contact = contact.next;
  81378. continue;
  81379. }
  81380. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  81381. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  81382. contact = contact.next;
  81383. }
  81384. };
  81385. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81386. var mass = impostor.physicsBody.mass;
  81387. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  81388. };
  81389. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81390. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  81391. this.applyImpulse(impostor, force, contactPoint);
  81392. };
  81393. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81394. var _this = this;
  81395. //parent-child relationship. Does this impostor has a parent impostor?
  81396. if (impostor.parent) {
  81397. if (impostor.physicsBody) {
  81398. this.removePhysicsBody(impostor);
  81399. //TODO is that needed?
  81400. impostor.forceUpdate();
  81401. }
  81402. return;
  81403. }
  81404. if (impostor.isBodyInitRequired()) {
  81405. var bodyConfig = {
  81406. name: impostor.uniqueId,
  81407. //Oimo must have mass, also for static objects.
  81408. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  81409. size: [],
  81410. type: [],
  81411. pos: [],
  81412. posShape: [],
  81413. rot: [],
  81414. rotShape: [],
  81415. move: impostor.getParam("mass") !== 0,
  81416. density: impostor.getParam("mass"),
  81417. friction: impostor.getParam("friction"),
  81418. restitution: impostor.getParam("restitution"),
  81419. //Supporting older versions of Oimo
  81420. world: this.world
  81421. };
  81422. var impostors = [impostor];
  81423. var addToArray = function (parent) {
  81424. if (!parent.getChildMeshes)
  81425. return;
  81426. parent.getChildMeshes().forEach(function (m) {
  81427. if (m.physicsImpostor) {
  81428. impostors.push(m.physicsImpostor);
  81429. //m.physicsImpostor._init();
  81430. }
  81431. });
  81432. };
  81433. addToArray(impostor.object);
  81434. var checkWithEpsilon_1 = function (value) {
  81435. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  81436. };
  81437. impostors.forEach(function (i) {
  81438. if (!i.object.rotationQuaternion) {
  81439. return;
  81440. }
  81441. //get the correct bounding box
  81442. var oldQuaternion = i.object.rotationQuaternion;
  81443. var rot = oldQuaternion.toEulerAngles();
  81444. var extendSize = i.getObjectExtendSize();
  81445. var radToDeg = 57.295779513082320876;
  81446. if (i === impostor) {
  81447. var center = impostor.getObjectCenter();
  81448. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  81449. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  81450. //Can also use Array.prototype.push.apply
  81451. bodyConfig.pos.push(center.x);
  81452. bodyConfig.pos.push(center.y);
  81453. bodyConfig.pos.push(center.z);
  81454. bodyConfig.posShape.push(0, 0, 0);
  81455. //tmp solution
  81456. bodyConfig.rot.push(rot.x * radToDeg);
  81457. bodyConfig.rot.push(rot.y * radToDeg);
  81458. bodyConfig.rot.push(rot.z * radToDeg);
  81459. bodyConfig.rotShape.push(0, 0, 0);
  81460. }
  81461. else {
  81462. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  81463. bodyConfig.posShape.push(localPosition.x);
  81464. bodyConfig.posShape.push(localPosition.y);
  81465. bodyConfig.posShape.push(localPosition.z);
  81466. bodyConfig.pos.push(0, 0, 0);
  81467. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  81468. bodyConfig.rot.push(0);
  81469. bodyConfig.rot.push(0);
  81470. bodyConfig.rot.push(0);
  81471. bodyConfig.rotShape.push(rot.x * radToDeg);
  81472. bodyConfig.rotShape.push(rot.y * radToDeg);
  81473. bodyConfig.rotShape.push(rot.z * radToDeg);
  81474. }
  81475. // register mesh
  81476. switch (i.type) {
  81477. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81478. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  81479. case BABYLON.PhysicsImpostor.SphereImpostor:
  81480. var radiusX = extendSize.x;
  81481. var radiusY = extendSize.y;
  81482. var radiusZ = extendSize.z;
  81483. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  81484. bodyConfig.type.push('sphere');
  81485. //due to the way oimo works with compounds, add 3 times
  81486. bodyConfig.size.push(size);
  81487. bodyConfig.size.push(size);
  81488. bodyConfig.size.push(size);
  81489. break;
  81490. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81491. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  81492. var sizeY = checkWithEpsilon_1(extendSize.y);
  81493. bodyConfig.type.push('cylinder');
  81494. bodyConfig.size.push(sizeX);
  81495. bodyConfig.size.push(sizeY);
  81496. //due to the way oimo works with compounds, add one more value.
  81497. bodyConfig.size.push(sizeY);
  81498. break;
  81499. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81500. case BABYLON.PhysicsImpostor.BoxImpostor:
  81501. default:
  81502. var sizeX = checkWithEpsilon_1(extendSize.x);
  81503. var sizeY = checkWithEpsilon_1(extendSize.y);
  81504. var sizeZ = checkWithEpsilon_1(extendSize.z);
  81505. bodyConfig.type.push('box');
  81506. //if (i === impostor) {
  81507. bodyConfig.size.push(sizeX);
  81508. bodyConfig.size.push(sizeY);
  81509. bodyConfig.size.push(sizeZ);
  81510. //} else {
  81511. // bodyConfig.size.push(0,0,0);
  81512. //}
  81513. break;
  81514. }
  81515. //actually not needed, but hey...
  81516. i.object.rotationQuaternion = oldQuaternion;
  81517. });
  81518. impostor.physicsBody = this.world.add(bodyConfig);
  81519. }
  81520. else {
  81521. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  81522. }
  81523. impostor.setDeltaPosition(this._tmpPositionVector);
  81524. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  81525. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  81526. };
  81527. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81528. //impostor.physicsBody.dispose();
  81529. //Same as : (older oimo versions)
  81530. this.world.removeRigidBody(impostor.physicsBody);
  81531. };
  81532. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81533. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81534. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81535. if (!mainBody || !connectedBody) {
  81536. return;
  81537. }
  81538. var jointData = impostorJoint.joint.jointData;
  81539. var options = jointData.nativeParams || {};
  81540. var type;
  81541. var nativeJointData = {
  81542. body1: mainBody,
  81543. body2: connectedBody,
  81544. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  81545. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  81546. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  81547. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  81548. min: options.min,
  81549. max: options.max,
  81550. collision: options.collision || jointData.collision,
  81551. spring: options.spring,
  81552. //supporting older version of Oimo
  81553. world: this.world
  81554. };
  81555. switch (impostorJoint.joint.type) {
  81556. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81557. type = "jointBall";
  81558. break;
  81559. case BABYLON.PhysicsJoint.SpringJoint:
  81560. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  81561. var springData = jointData;
  81562. nativeJointData.min = springData.length || nativeJointData.min;
  81563. //Max should also be set, just make sure it is at least min
  81564. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  81565. case BABYLON.PhysicsJoint.DistanceJoint:
  81566. type = "jointDistance";
  81567. nativeJointData.max = jointData.maxDistance;
  81568. break;
  81569. case BABYLON.PhysicsJoint.PrismaticJoint:
  81570. type = "jointPrisme";
  81571. break;
  81572. case BABYLON.PhysicsJoint.SliderJoint:
  81573. type = "jointSlide";
  81574. break;
  81575. case BABYLON.PhysicsJoint.WheelJoint:
  81576. type = "jointWheel";
  81577. break;
  81578. case BABYLON.PhysicsJoint.HingeJoint:
  81579. default:
  81580. type = "jointHinge";
  81581. break;
  81582. }
  81583. nativeJointData.type = type;
  81584. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  81585. };
  81586. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81587. //Bug in Oimo prevents us from disposing a joint in the playground
  81588. //joint.joint.physicsJoint.dispose();
  81589. //So we will bruteforce it!
  81590. try {
  81591. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  81592. }
  81593. catch (e) {
  81594. BABYLON.Tools.Warn(e);
  81595. }
  81596. };
  81597. OimoJSPlugin.prototype.isSupported = function () {
  81598. return this.BJSOIMO !== undefined;
  81599. };
  81600. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81601. if (!impostor.physicsBody.sleeping) {
  81602. //TODO check that
  81603. /*if (impostor.physicsBody.shapes.next) {
  81604. var parentShape = this._getLastShape(impostor.physicsBody);
  81605. impostor.object.position.copyFrom(parentShape.position);
  81606. console.log(parentShape.position);
  81607. } else {*/
  81608. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  81609. //}
  81610. if (impostor.object.rotationQuaternion) {
  81611. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  81612. }
  81613. }
  81614. };
  81615. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81616. var body = impostor.physicsBody;
  81617. body.position.copy(newPosition);
  81618. body.orientation.copy(newRotation);
  81619. body.syncShapes();
  81620. body.awake();
  81621. };
  81622. /*private _getLastShape(body: any): any {
  81623. var lastShape = body.shapes;
  81624. while (lastShape.next) {
  81625. lastShape = lastShape.next;
  81626. }
  81627. return lastShape;
  81628. }*/
  81629. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81630. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  81631. };
  81632. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81633. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  81634. };
  81635. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81636. var v = impostor.physicsBody.linearVelocity;
  81637. if (!v) {
  81638. return null;
  81639. }
  81640. return new BABYLON.Vector3(v.x, v.y, v.z);
  81641. };
  81642. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81643. var v = impostor.physicsBody.angularVelocity;
  81644. if (!v) {
  81645. return null;
  81646. }
  81647. return new BABYLON.Vector3(v.x, v.y, v.z);
  81648. };
  81649. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81650. var staticBody = mass === 0;
  81651. //this will actually set the body's density and not its mass.
  81652. //But this is how oimo treats the mass variable.
  81653. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  81654. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  81655. };
  81656. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  81657. return impostor.physicsBody.shapes.density;
  81658. };
  81659. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  81660. return impostor.physicsBody.shapes.friction;
  81661. };
  81662. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81663. impostor.physicsBody.shapes.friction = friction;
  81664. };
  81665. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81666. return impostor.physicsBody.shapes.restitution;
  81667. };
  81668. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81669. impostor.physicsBody.shapes.restitution = restitution;
  81670. };
  81671. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  81672. impostor.physicsBody.sleep();
  81673. };
  81674. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  81675. impostor.physicsBody.awake();
  81676. };
  81677. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81678. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  81679. if (minDistance !== void 0) {
  81680. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  81681. }
  81682. };
  81683. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81684. //TODO separate rotational and transational motors.
  81685. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  81686. if (motor) {
  81687. motor.setMotor(speed, maxForce);
  81688. }
  81689. };
  81690. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  81691. //TODO separate rotational and transational motors.
  81692. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  81693. if (motor) {
  81694. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  81695. }
  81696. };
  81697. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81698. var body = impostor.physicsBody;
  81699. mesh.position.x = body.position.x;
  81700. mesh.position.y = body.position.y;
  81701. mesh.position.z = body.position.z;
  81702. if (mesh.rotationQuaternion) {
  81703. mesh.rotationQuaternion.x = body.orientation.x;
  81704. mesh.rotationQuaternion.y = body.orientation.y;
  81705. mesh.rotationQuaternion.z = body.orientation.z;
  81706. mesh.rotationQuaternion.w = body.orientation.s;
  81707. }
  81708. };
  81709. OimoJSPlugin.prototype.getRadius = function (impostor) {
  81710. return impostor.physicsBody.shapes.radius;
  81711. };
  81712. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81713. var shape = impostor.physicsBody.shapes;
  81714. result.x = shape.halfWidth * 2;
  81715. result.y = shape.halfHeight * 2;
  81716. result.z = shape.halfDepth * 2;
  81717. };
  81718. OimoJSPlugin.prototype.dispose = function () {
  81719. this.world.clear();
  81720. };
  81721. return OimoJSPlugin;
  81722. }());
  81723. BABYLON.OimoJSPlugin = OimoJSPlugin;
  81724. })(BABYLON || (BABYLON = {}));
  81725. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  81726. "use strict";
  81727. var BABYLON;
  81728. (function (BABYLON) {
  81729. /*
  81730. * Based on jsTGALoader - Javascript loader for TGA file
  81731. * By Vincent Thibault
  81732. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  81733. */
  81734. var TGATools = /** @class */ (function () {
  81735. function TGATools() {
  81736. }
  81737. TGATools.GetTGAHeader = function (data) {
  81738. var offset = 0;
  81739. var header = {
  81740. id_length: data[offset++],
  81741. colormap_type: data[offset++],
  81742. image_type: data[offset++],
  81743. colormap_index: data[offset++] | data[offset++] << 8,
  81744. colormap_length: data[offset++] | data[offset++] << 8,
  81745. colormap_size: data[offset++],
  81746. origin: [
  81747. data[offset++] | data[offset++] << 8,
  81748. data[offset++] | data[offset++] << 8
  81749. ],
  81750. width: data[offset++] | data[offset++] << 8,
  81751. height: data[offset++] | data[offset++] << 8,
  81752. pixel_size: data[offset++],
  81753. flags: data[offset++]
  81754. };
  81755. return header;
  81756. };
  81757. TGATools.UploadContent = function (gl, data) {
  81758. // Not enough data to contain header ?
  81759. if (data.length < 19) {
  81760. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  81761. return;
  81762. }
  81763. // Read Header
  81764. var offset = 18;
  81765. var header = TGATools.GetTGAHeader(data);
  81766. // Assume it's a valid Targa file.
  81767. if (header.id_length + offset > data.length) {
  81768. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  81769. return;
  81770. }
  81771. // Skip not needed data
  81772. offset += header.id_length;
  81773. var use_rle = false;
  81774. var use_pal = false;
  81775. var use_grey = false;
  81776. // Get some informations.
  81777. switch (header.image_type) {
  81778. case TGATools._TYPE_RLE_INDEXED:
  81779. use_rle = true;
  81780. case TGATools._TYPE_INDEXED:
  81781. use_pal = true;
  81782. break;
  81783. case TGATools._TYPE_RLE_RGB:
  81784. use_rle = true;
  81785. case TGATools._TYPE_RGB:
  81786. // use_rgb = true;
  81787. break;
  81788. case TGATools._TYPE_RLE_GREY:
  81789. use_rle = true;
  81790. case TGATools._TYPE_GREY:
  81791. use_grey = true;
  81792. break;
  81793. }
  81794. var pixel_data;
  81795. // var numAlphaBits = header.flags & 0xf;
  81796. var pixel_size = header.pixel_size >> 3;
  81797. var pixel_total = header.width * header.height * pixel_size;
  81798. // Read palettes
  81799. var palettes;
  81800. if (use_pal) {
  81801. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  81802. }
  81803. // Read LRE
  81804. if (use_rle) {
  81805. pixel_data = new Uint8Array(pixel_total);
  81806. var c, count, i;
  81807. var localOffset = 0;
  81808. var pixels = new Uint8Array(pixel_size);
  81809. while (offset < pixel_total && localOffset < pixel_total) {
  81810. c = data[offset++];
  81811. count = (c & 0x7f) + 1;
  81812. // RLE pixels
  81813. if (c & 0x80) {
  81814. // Bind pixel tmp array
  81815. for (i = 0; i < pixel_size; ++i) {
  81816. pixels[i] = data[offset++];
  81817. }
  81818. // Copy pixel array
  81819. for (i = 0; i < count; ++i) {
  81820. pixel_data.set(pixels, localOffset + i * pixel_size);
  81821. }
  81822. localOffset += pixel_size * count;
  81823. }
  81824. else {
  81825. count *= pixel_size;
  81826. for (i = 0; i < count; ++i) {
  81827. pixel_data[localOffset + i] = data[offset++];
  81828. }
  81829. localOffset += count;
  81830. }
  81831. }
  81832. }
  81833. else {
  81834. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  81835. }
  81836. // Load to texture
  81837. var x_start, y_start, x_step, y_step, y_end, x_end;
  81838. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  81839. default:
  81840. case TGATools._ORIGIN_UL:
  81841. x_start = 0;
  81842. x_step = 1;
  81843. x_end = header.width;
  81844. y_start = 0;
  81845. y_step = 1;
  81846. y_end = header.height;
  81847. break;
  81848. case TGATools._ORIGIN_BL:
  81849. x_start = 0;
  81850. x_step = 1;
  81851. x_end = header.width;
  81852. y_start = header.height - 1;
  81853. y_step = -1;
  81854. y_end = -1;
  81855. break;
  81856. case TGATools._ORIGIN_UR:
  81857. x_start = header.width - 1;
  81858. x_step = -1;
  81859. x_end = -1;
  81860. y_start = 0;
  81861. y_step = 1;
  81862. y_end = header.height;
  81863. break;
  81864. case TGATools._ORIGIN_BR:
  81865. x_start = header.width - 1;
  81866. x_step = -1;
  81867. x_end = -1;
  81868. y_start = header.height - 1;
  81869. y_step = -1;
  81870. y_end = -1;
  81871. break;
  81872. }
  81873. // Load the specify method
  81874. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  81875. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  81876. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  81877. };
  81878. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81879. var image = pixel_data, colormap = palettes;
  81880. var width = header.width, height = header.height;
  81881. var color, i = 0, x, y;
  81882. var imageData = new Uint8Array(width * height * 4);
  81883. for (y = y_start; y !== y_end; y += y_step) {
  81884. for (x = x_start; x !== x_end; x += x_step, i++) {
  81885. color = image[i];
  81886. imageData[(x + width * y) * 4 + 3] = 255;
  81887. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  81888. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  81889. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  81890. }
  81891. }
  81892. return imageData;
  81893. };
  81894. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81895. var image = pixel_data;
  81896. var width = header.width, height = header.height;
  81897. var color, i = 0, x, y;
  81898. var imageData = new Uint8Array(width * height * 4);
  81899. for (y = y_start; y !== y_end; y += y_step) {
  81900. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  81901. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  81902. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  81903. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  81904. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  81905. imageData[(x + width * y) * 4 + 0] = r;
  81906. imageData[(x + width * y) * 4 + 1] = g;
  81907. imageData[(x + width * y) * 4 + 2] = b;
  81908. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  81909. }
  81910. }
  81911. return imageData;
  81912. };
  81913. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81914. var image = pixel_data;
  81915. var width = header.width, height = header.height;
  81916. var i = 0, x, y;
  81917. var imageData = new Uint8Array(width * height * 4);
  81918. for (y = y_start; y !== y_end; y += y_step) {
  81919. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  81920. imageData[(x + width * y) * 4 + 3] = 255;
  81921. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81922. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  81923. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  81924. }
  81925. }
  81926. return imageData;
  81927. };
  81928. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81929. var image = pixel_data;
  81930. var width = header.width, height = header.height;
  81931. var i = 0, x, y;
  81932. var imageData = new Uint8Array(width * height * 4);
  81933. for (y = y_start; y !== y_end; y += y_step) {
  81934. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  81935. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81936. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  81937. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  81938. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  81939. }
  81940. }
  81941. return imageData;
  81942. };
  81943. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81944. var image = pixel_data;
  81945. var width = header.width, height = header.height;
  81946. var color, i = 0, x, y;
  81947. var imageData = new Uint8Array(width * height * 4);
  81948. for (y = y_start; y !== y_end; y += y_step) {
  81949. for (x = x_start; x !== x_end; x += x_step, i++) {
  81950. color = image[i];
  81951. imageData[(x + width * y) * 4 + 0] = color;
  81952. imageData[(x + width * y) * 4 + 1] = color;
  81953. imageData[(x + width * y) * 4 + 2] = color;
  81954. imageData[(x + width * y) * 4 + 3] = 255;
  81955. }
  81956. }
  81957. return imageData;
  81958. };
  81959. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81960. var image = pixel_data;
  81961. var width = header.width, height = header.height;
  81962. var i = 0, x, y;
  81963. var imageData = new Uint8Array(width * height * 4);
  81964. for (y = y_start; y !== y_end; y += y_step) {
  81965. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  81966. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  81967. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  81968. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81969. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  81970. }
  81971. }
  81972. return imageData;
  81973. };
  81974. //private static _TYPE_NO_DATA = 0;
  81975. TGATools._TYPE_INDEXED = 1;
  81976. TGATools._TYPE_RGB = 2;
  81977. TGATools._TYPE_GREY = 3;
  81978. TGATools._TYPE_RLE_INDEXED = 9;
  81979. TGATools._TYPE_RLE_RGB = 10;
  81980. TGATools._TYPE_RLE_GREY = 11;
  81981. TGATools._ORIGIN_MASK = 0x30;
  81982. TGATools._ORIGIN_SHIFT = 0x04;
  81983. TGATools._ORIGIN_BL = 0x00;
  81984. TGATools._ORIGIN_BR = 0x01;
  81985. TGATools._ORIGIN_UL = 0x02;
  81986. TGATools._ORIGIN_UR = 0x03;
  81987. return TGATools;
  81988. }());
  81989. BABYLON.TGATools = TGATools;
  81990. })(BABYLON || (BABYLON = {}));
  81991. //# sourceMappingURL=babylon.tga.js.map
  81992. "use strict";
  81993. var BABYLON;
  81994. (function (BABYLON) {
  81995. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  81996. // All values and structures referenced from:
  81997. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  81998. var DDS_MAGIC = 0x20534444;
  81999. var
  82000. //DDSD_CAPS = 0x1,
  82001. //DDSD_HEIGHT = 0x2,
  82002. //DDSD_WIDTH = 0x4,
  82003. //DDSD_PITCH = 0x8,
  82004. //DDSD_PIXELFORMAT = 0x1000,
  82005. DDSD_MIPMAPCOUNT = 0x20000;
  82006. //DDSD_LINEARSIZE = 0x80000,
  82007. //DDSD_DEPTH = 0x800000;
  82008. // var DDSCAPS_COMPLEX = 0x8,
  82009. // DDSCAPS_MIPMAP = 0x400000,
  82010. // DDSCAPS_TEXTURE = 0x1000;
  82011. var DDSCAPS2_CUBEMAP = 0x200;
  82012. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  82013. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  82014. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  82015. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  82016. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  82017. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  82018. // DDSCAPS2_VOLUME = 0x200000;
  82019. var
  82020. //DDPF_ALPHAPIXELS = 0x1,
  82021. //DDPF_ALPHA = 0x2,
  82022. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  82023. //DDPF_YUV = 0x200,
  82024. DDPF_LUMINANCE = 0x20000;
  82025. function FourCCToInt32(value) {
  82026. return value.charCodeAt(0) +
  82027. (value.charCodeAt(1) << 8) +
  82028. (value.charCodeAt(2) << 16) +
  82029. (value.charCodeAt(3) << 24);
  82030. }
  82031. function Int32ToFourCC(value) {
  82032. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  82033. }
  82034. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  82035. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  82036. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  82037. var FOURCC_DX10 = FourCCToInt32("DX10");
  82038. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  82039. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  82040. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  82041. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  82042. var headerLengthInt = 31; // The header length in 32 bit ints
  82043. // Offsets into the header array
  82044. var off_magic = 0;
  82045. var off_size = 1;
  82046. var off_flags = 2;
  82047. var off_height = 3;
  82048. var off_width = 4;
  82049. var off_mipmapCount = 7;
  82050. var off_pfFlags = 20;
  82051. var off_pfFourCC = 21;
  82052. var off_RGBbpp = 22;
  82053. var off_RMask = 23;
  82054. var off_GMask = 24;
  82055. var off_BMask = 25;
  82056. var off_AMask = 26;
  82057. // var off_caps1 = 27;
  82058. var off_caps2 = 28;
  82059. // var off_caps3 = 29;
  82060. // var off_caps4 = 30;
  82061. var off_dxgiFormat = 32;
  82062. ;
  82063. var DDSTools = /** @class */ (function () {
  82064. function DDSTools() {
  82065. }
  82066. DDSTools.GetDDSInfo = function (arrayBuffer) {
  82067. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82068. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  82069. var mipmapCount = 1;
  82070. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  82071. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82072. }
  82073. var fourCC = header[off_pfFourCC];
  82074. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  82075. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82076. switch (fourCC) {
  82077. case FOURCC_D3DFMT_R16G16B16A16F:
  82078. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82079. break;
  82080. case FOURCC_D3DFMT_R32G32B32A32F:
  82081. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82082. break;
  82083. case FOURCC_DX10:
  82084. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  82085. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82086. break;
  82087. }
  82088. }
  82089. return {
  82090. width: header[off_width],
  82091. height: header[off_height],
  82092. mipmapCount: mipmapCount,
  82093. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  82094. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  82095. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  82096. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  82097. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  82098. dxgiFormat: dxgiFormat,
  82099. textureType: textureType
  82100. };
  82101. };
  82102. DDSTools._ToHalfFloat = function (value) {
  82103. if (!DDSTools._FloatView) {
  82104. DDSTools._FloatView = new Float32Array(1);
  82105. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  82106. }
  82107. DDSTools._FloatView[0] = value;
  82108. var x = DDSTools._Int32View[0];
  82109. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82110. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82111. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82112. /* If zero, or denormal, or exponent underflows too much for a denormal
  82113. * half, return signed zero. */
  82114. if (e < 103) {
  82115. return bits;
  82116. }
  82117. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82118. if (e > 142) {
  82119. bits |= 0x7c00;
  82120. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82121. * not Inf, so make sure we set one mantissa bit too. */
  82122. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82123. return bits;
  82124. }
  82125. /* If exponent underflows but not too much, return a denormal */
  82126. if (e < 113) {
  82127. m |= 0x0800;
  82128. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82129. * to 1, which is OK. */
  82130. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82131. return bits;
  82132. }
  82133. bits |= ((e - 112) << 10) | (m >> 1);
  82134. bits += m & 1;
  82135. return bits;
  82136. };
  82137. DDSTools._FromHalfFloat = function (value) {
  82138. var s = (value & 0x8000) >> 15;
  82139. var e = (value & 0x7C00) >> 10;
  82140. var f = value & 0x03FF;
  82141. if (e === 0) {
  82142. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82143. }
  82144. else if (e == 0x1F) {
  82145. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82146. }
  82147. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82148. };
  82149. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82150. var destArray = new Float32Array(dataLength);
  82151. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82152. var index = 0;
  82153. for (var y = 0; y < height; y++) {
  82154. for (var x = 0; x < width; x++) {
  82155. var srcPos = (x + y * width) * 4;
  82156. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82157. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82158. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82159. if (DDSTools.StoreLODInAlphaChannel) {
  82160. destArray[index + 3] = lod;
  82161. }
  82162. else {
  82163. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82164. }
  82165. index += 4;
  82166. }
  82167. }
  82168. return destArray;
  82169. };
  82170. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82171. if (DDSTools.StoreLODInAlphaChannel) {
  82172. var destArray = new Uint16Array(dataLength);
  82173. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82174. var index = 0;
  82175. for (var y = 0; y < height; y++) {
  82176. for (var x = 0; x < width; x++) {
  82177. var srcPos = (x + y * width) * 4;
  82178. destArray[index] = srcData[srcPos];
  82179. destArray[index + 1] = srcData[srcPos + 1];
  82180. destArray[index + 2] = srcData[srcPos + 2];
  82181. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82182. index += 4;
  82183. }
  82184. }
  82185. return destArray;
  82186. }
  82187. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82188. };
  82189. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82190. if (DDSTools.StoreLODInAlphaChannel) {
  82191. var destArray = new Float32Array(dataLength);
  82192. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82193. var index = 0;
  82194. for (var y = 0; y < height; y++) {
  82195. for (var x = 0; x < width; x++) {
  82196. var srcPos = (x + y * width) * 4;
  82197. destArray[index] = srcData[srcPos];
  82198. destArray[index + 1] = srcData[srcPos + 1];
  82199. destArray[index + 2] = srcData[srcPos + 2];
  82200. destArray[index + 3] = lod;
  82201. index += 4;
  82202. }
  82203. }
  82204. return destArray;
  82205. }
  82206. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  82207. };
  82208. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82209. var destArray = new Uint8Array(dataLength);
  82210. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82211. var index = 0;
  82212. for (var y = 0; y < height; y++) {
  82213. for (var x = 0; x < width; x++) {
  82214. var srcPos = (x + y * width) * 4;
  82215. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  82216. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  82217. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  82218. if (DDSTools.StoreLODInAlphaChannel) {
  82219. destArray[index + 3] = lod;
  82220. }
  82221. else {
  82222. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  82223. }
  82224. index += 4;
  82225. }
  82226. }
  82227. return destArray;
  82228. };
  82229. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82230. var destArray = new Uint8Array(dataLength);
  82231. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82232. var index = 0;
  82233. for (var y = 0; y < height; y++) {
  82234. for (var x = 0; x < width; x++) {
  82235. var srcPos = (x + y * width) * 4;
  82236. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  82237. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  82238. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  82239. if (DDSTools.StoreLODInAlphaChannel) {
  82240. destArray[index + 3] = lod;
  82241. }
  82242. else {
  82243. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  82244. }
  82245. index += 4;
  82246. }
  82247. }
  82248. return destArray;
  82249. };
  82250. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  82251. var byteArray = new Uint8Array(dataLength);
  82252. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82253. var index = 0;
  82254. for (var y = 0; y < height; y++) {
  82255. for (var x = 0; x < width; x++) {
  82256. var srcPos = (x + y * width) * 4;
  82257. byteArray[index] = srcData[srcPos + rOffset];
  82258. byteArray[index + 1] = srcData[srcPos + gOffset];
  82259. byteArray[index + 2] = srcData[srcPos + bOffset];
  82260. byteArray[index + 3] = srcData[srcPos + aOffset];
  82261. index += 4;
  82262. }
  82263. }
  82264. return byteArray;
  82265. };
  82266. DDSTools._ExtractLongWordOrder = function (value) {
  82267. if (value === 0 || value === 255 || value === -16777216) {
  82268. return 0;
  82269. }
  82270. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  82271. };
  82272. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  82273. var byteArray = new Uint8Array(dataLength);
  82274. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82275. var index = 0;
  82276. for (var y = 0; y < height; y++) {
  82277. for (var x = 0; x < width; x++) {
  82278. var srcPos = (x + y * width) * 3;
  82279. byteArray[index] = srcData[srcPos + rOffset];
  82280. byteArray[index + 1] = srcData[srcPos + gOffset];
  82281. byteArray[index + 2] = srcData[srcPos + bOffset];
  82282. index += 3;
  82283. }
  82284. }
  82285. return byteArray;
  82286. };
  82287. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  82288. var byteArray = new Uint8Array(dataLength);
  82289. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82290. var index = 0;
  82291. for (var y = 0; y < height; y++) {
  82292. for (var x = 0; x < width; x++) {
  82293. var srcPos = (x + y * width);
  82294. byteArray[index] = srcData[srcPos];
  82295. index++;
  82296. }
  82297. }
  82298. return byteArray;
  82299. };
  82300. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  82301. if (lodIndex === void 0) { lodIndex = -1; }
  82302. var ext = engine.getCaps().s3tc;
  82303. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82304. var fourCC, width, height, dataLength = 0, dataOffset;
  82305. var byteArray, mipmapCount, mip;
  82306. var internalFormat = 0;
  82307. var format = 0;
  82308. var blockBytes = 1;
  82309. if (header[off_magic] !== DDS_MAGIC) {
  82310. BABYLON.Tools.Error("Invalid magic number in DDS header");
  82311. return;
  82312. }
  82313. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  82314. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  82315. return;
  82316. }
  82317. if (info.isCompressed && !ext) {
  82318. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  82319. return;
  82320. }
  82321. var bpp = header[off_RGBbpp];
  82322. dataOffset = header[off_size] + 4;
  82323. var computeFormats = false;
  82324. if (info.isFourCC) {
  82325. fourCC = header[off_pfFourCC];
  82326. switch (fourCC) {
  82327. case FOURCC_DXT1:
  82328. blockBytes = 8;
  82329. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  82330. break;
  82331. case FOURCC_DXT3:
  82332. blockBytes = 16;
  82333. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  82334. break;
  82335. case FOURCC_DXT5:
  82336. blockBytes = 16;
  82337. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  82338. break;
  82339. case FOURCC_D3DFMT_R16G16B16A16F:
  82340. computeFormats = true;
  82341. break;
  82342. case FOURCC_D3DFMT_R32G32B32A32F:
  82343. computeFormats = true;
  82344. break;
  82345. case FOURCC_DX10:
  82346. // There is an additionnal header so dataOffset need to be changed
  82347. dataOffset += 5 * 4; // 5 uints
  82348. var supported = false;
  82349. switch (info.dxgiFormat) {
  82350. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  82351. computeFormats = true;
  82352. supported = true;
  82353. break;
  82354. case DXGI_FORMAT_B8G8R8X8_UNORM:
  82355. info.isRGB = true;
  82356. info.isFourCC = false;
  82357. bpp = 32;
  82358. supported = true;
  82359. break;
  82360. }
  82361. if (supported) {
  82362. break;
  82363. }
  82364. default:
  82365. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  82366. return;
  82367. }
  82368. }
  82369. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  82370. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  82371. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  82372. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  82373. if (computeFormats) {
  82374. format = engine._getWebGLTextureType(info.textureType);
  82375. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82376. }
  82377. mipmapCount = 1;
  82378. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  82379. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82380. }
  82381. for (var face = 0; face < faces; face++) {
  82382. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  82383. width = header[off_width];
  82384. height = header[off_height];
  82385. for (mip = 0; mip < mipmapCount; ++mip) {
  82386. if (lodIndex === -1 || lodIndex === mip) {
  82387. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  82388. var i = (lodIndex === -1) ? mip : 0;
  82389. if (!info.isCompressed && info.isFourCC) {
  82390. dataLength = width * height * 4;
  82391. var floatArray = null;
  82392. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  82393. if (bpp === 128) {
  82394. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82395. }
  82396. else if (bpp === 64) {
  82397. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82398. }
  82399. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82400. format = engine._getWebGLTextureType(info.textureType);
  82401. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82402. }
  82403. else {
  82404. if (bpp === 128) {
  82405. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82406. }
  82407. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  82408. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82409. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82410. format = engine._getWebGLTextureType(info.textureType);
  82411. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82412. }
  82413. else {
  82414. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82415. }
  82416. }
  82417. if (floatArray) {
  82418. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  82419. }
  82420. }
  82421. else if (info.isRGB) {
  82422. if (bpp === 24) {
  82423. dataLength = width * height * 3;
  82424. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  82425. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  82426. }
  82427. else {
  82428. dataLength = width * height * 4;
  82429. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  82430. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  82431. }
  82432. }
  82433. else if (info.isLuminance) {
  82434. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  82435. var unpaddedRowSize = width;
  82436. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  82437. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  82438. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  82439. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  82440. }
  82441. else {
  82442. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  82443. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  82444. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  82445. }
  82446. }
  82447. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  82448. width *= 0.5;
  82449. height *= 0.5;
  82450. width = Math.max(1.0, width);
  82451. height = Math.max(1.0, height);
  82452. }
  82453. if (currentFace !== undefined) {
  82454. // Loading a single face
  82455. break;
  82456. }
  82457. }
  82458. };
  82459. DDSTools.StoreLODInAlphaChannel = false;
  82460. return DDSTools;
  82461. }());
  82462. BABYLON.DDSTools = DDSTools;
  82463. })(BABYLON || (BABYLON = {}));
  82464. //# sourceMappingURL=babylon.dds.js.map
  82465. "use strict";
  82466. var BABYLON;
  82467. (function (BABYLON) {
  82468. /**
  82469. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  82470. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  82471. */
  82472. var KhronosTextureContainer = /** @class */ (function () {
  82473. /**
  82474. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  82475. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  82476. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  82477. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  82478. */
  82479. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  82480. this.arrayBuffer = arrayBuffer;
  82481. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  82482. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  82483. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  82484. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  82485. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  82486. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  82487. BABYLON.Tools.Error("texture missing KTX identifier");
  82488. return;
  82489. }
  82490. // load the reset of the header in native 32 bit int
  82491. var header = new Int32Array(this.arrayBuffer, 12, 13);
  82492. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  82493. var oppositeEndianess = header[0] === 0x01020304;
  82494. // read all the header elements in order they exist in the file, without modification (sans endainness)
  82495. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  82496. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  82497. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  82498. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  82499. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  82500. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  82501. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  82502. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  82503. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  82504. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  82505. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  82506. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  82507. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  82508. if (this.glType !== 0) {
  82509. BABYLON.Tools.Error("only compressed formats currently supported");
  82510. return;
  82511. }
  82512. else {
  82513. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  82514. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  82515. }
  82516. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  82517. BABYLON.Tools.Error("only 2D textures currently supported");
  82518. return;
  82519. }
  82520. if (this.numberOfArrayElements !== 0) {
  82521. BABYLON.Tools.Error("texture arrays not currently supported");
  82522. return;
  82523. }
  82524. if (this.numberOfFaces !== facesExpected) {
  82525. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  82526. return;
  82527. }
  82528. // we now have a completely validated file, so could use existence of loadType as success
  82529. // would need to make this more elaborate & adjust checks above to support more than one load type
  82530. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  82531. }
  82532. // not as fast hardware based, but will probably never need to use
  82533. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  82534. return ((val & 0xFF) << 24)
  82535. | ((val & 0xFF00) << 8)
  82536. | ((val >> 8) & 0xFF00)
  82537. | ((val >> 24) & 0xFF);
  82538. };
  82539. /**
  82540. * It is assumed that the texture has already been created & is currently bound
  82541. */
  82542. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  82543. switch (this.loadType) {
  82544. case KhronosTextureContainer.COMPRESSED_2D:
  82545. this._upload2DCompressedLevels(gl, loadMipmaps);
  82546. break;
  82547. case KhronosTextureContainer.TEX_2D:
  82548. case KhronosTextureContainer.COMPRESSED_3D:
  82549. case KhronosTextureContainer.TEX_3D:
  82550. }
  82551. };
  82552. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  82553. // initialize width & height for level 1
  82554. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  82555. var width = this.pixelWidth;
  82556. var height = this.pixelHeight;
  82557. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  82558. for (var level = 0; level < mipmapCount; level++) {
  82559. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  82560. for (var face = 0; face < this.numberOfFaces; face++) {
  82561. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  82562. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  82563. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  82564. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  82565. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  82566. }
  82567. width = Math.max(1.0, width * 0.5);
  82568. height = Math.max(1.0, height * 0.5);
  82569. }
  82570. };
  82571. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  82572. // load types
  82573. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  82574. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  82575. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  82576. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  82577. return KhronosTextureContainer;
  82578. }());
  82579. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  82580. })(BABYLON || (BABYLON = {}));
  82581. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  82582. "use strict";
  82583. var BABYLON;
  82584. (function (BABYLON) {
  82585. var Debug;
  82586. (function (Debug) {
  82587. /**
  82588. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  82589. */
  82590. var SkeletonViewer = /** @class */ (function () {
  82591. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  82592. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  82593. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  82594. this.skeleton = skeleton;
  82595. this.mesh = mesh;
  82596. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  82597. this.renderingGroupId = renderingGroupId;
  82598. this.color = BABYLON.Color3.White();
  82599. this._debugLines = new Array();
  82600. this._isEnabled = false;
  82601. this._scene = scene;
  82602. this.update();
  82603. this._renderFunction = this.update.bind(this);
  82604. }
  82605. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  82606. get: function () {
  82607. return this._isEnabled;
  82608. },
  82609. set: function (value) {
  82610. if (this._isEnabled === value) {
  82611. return;
  82612. }
  82613. this._isEnabled = value;
  82614. if (value) {
  82615. this._scene.registerBeforeRender(this._renderFunction);
  82616. }
  82617. else {
  82618. this._scene.unregisterBeforeRender(this._renderFunction);
  82619. }
  82620. },
  82621. enumerable: true,
  82622. configurable: true
  82623. });
  82624. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  82625. if (x === void 0) { x = 0; }
  82626. if (y === void 0) { y = 0; }
  82627. if (z === void 0) { z = 0; }
  82628. var tmat = BABYLON.Tmp.Matrix[0];
  82629. var parentBone = bone.getParent();
  82630. tmat.copyFrom(bone.getLocalMatrix());
  82631. if (x !== 0 || y !== 0 || z !== 0) {
  82632. var tmat2 = BABYLON.Tmp.Matrix[1];
  82633. BABYLON.Matrix.IdentityToRef(tmat2);
  82634. tmat2.m[12] = x;
  82635. tmat2.m[13] = y;
  82636. tmat2.m[14] = z;
  82637. tmat2.multiplyToRef(tmat, tmat);
  82638. }
  82639. if (parentBone) {
  82640. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  82641. }
  82642. tmat.multiplyToRef(meshMat, tmat);
  82643. position.x = tmat.m[12];
  82644. position.y = tmat.m[13];
  82645. position.z = tmat.m[14];
  82646. };
  82647. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  82648. var len = bones.length;
  82649. var meshPos = this.mesh.position;
  82650. for (var i = 0; i < len; i++) {
  82651. var bone = bones[i];
  82652. var points = this._debugLines[i];
  82653. if (!points) {
  82654. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82655. this._debugLines[i] = points;
  82656. }
  82657. this._getBonePosition(points[0], bone, meshMat);
  82658. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  82659. points[0].subtractInPlace(meshPos);
  82660. points[1].subtractInPlace(meshPos);
  82661. }
  82662. };
  82663. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  82664. var len = bones.length;
  82665. var boneNum = 0;
  82666. var meshPos = this.mesh.position;
  82667. for (var i = len - 1; i >= 0; i--) {
  82668. var childBone = bones[i];
  82669. var parentBone = childBone.getParent();
  82670. if (!parentBone) {
  82671. continue;
  82672. }
  82673. var points = this._debugLines[boneNum];
  82674. if (!points) {
  82675. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82676. this._debugLines[boneNum] = points;
  82677. }
  82678. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  82679. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  82680. points[0].subtractInPlace(meshPos);
  82681. points[1].subtractInPlace(meshPos);
  82682. boneNum++;
  82683. }
  82684. };
  82685. SkeletonViewer.prototype.update = function () {
  82686. if (this.autoUpdateBonesMatrices) {
  82687. this.skeleton.computeAbsoluteTransforms();
  82688. }
  82689. if (this.skeleton.bones[0].length === undefined) {
  82690. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  82691. }
  82692. else {
  82693. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  82694. }
  82695. if (!this._debugMesh) {
  82696. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  82697. this._debugMesh.renderingGroupId = this.renderingGroupId;
  82698. }
  82699. else {
  82700. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  82701. }
  82702. this._debugMesh.position.copyFrom(this.mesh.position);
  82703. this._debugMesh.color = this.color;
  82704. };
  82705. SkeletonViewer.prototype.dispose = function () {
  82706. if (this._debugMesh) {
  82707. this.isEnabled = false;
  82708. this._debugMesh.dispose();
  82709. this._debugMesh = null;
  82710. }
  82711. };
  82712. return SkeletonViewer;
  82713. }());
  82714. Debug.SkeletonViewer = SkeletonViewer;
  82715. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82716. })(BABYLON || (BABYLON = {}));
  82717. //# sourceMappingURL=babylon.skeletonViewer.js.map
  82718. "use strict";
  82719. /**
  82720. * Module Debug contains the (visual) components to debug a scene correctly
  82721. */
  82722. var BABYLON;
  82723. (function (BABYLON) {
  82724. var Debug;
  82725. (function (Debug) {
  82726. /**
  82727. * The Axes viewer will show 3 axes in a specific point in space
  82728. */
  82729. var AxesViewer = /** @class */ (function () {
  82730. function AxesViewer(scene, scaleLines) {
  82731. if (scaleLines === void 0) { scaleLines = 1; }
  82732. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82733. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82734. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82735. this.scaleLines = 1;
  82736. this.scaleLines = scaleLines;
  82737. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  82738. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  82739. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  82740. this._xmesh.renderingGroupId = 2;
  82741. this._ymesh.renderingGroupId = 2;
  82742. this._zmesh.renderingGroupId = 2;
  82743. this._xmesh.material.checkReadyOnlyOnce = true;
  82744. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  82745. this._ymesh.material.checkReadyOnlyOnce = true;
  82746. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  82747. this._zmesh.material.checkReadyOnlyOnce = true;
  82748. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  82749. this.scene = scene;
  82750. }
  82751. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  82752. var scaleLines = this.scaleLines;
  82753. if (this._xmesh) {
  82754. this._xmesh.position.copyFrom(position);
  82755. }
  82756. if (this._ymesh) {
  82757. this._ymesh.position.copyFrom(position);
  82758. }
  82759. if (this._zmesh) {
  82760. this._zmesh.position.copyFrom(position);
  82761. }
  82762. var point2 = this._xline[1];
  82763. point2.x = xaxis.x * scaleLines;
  82764. point2.y = xaxis.y * scaleLines;
  82765. point2.z = xaxis.z * scaleLines;
  82766. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  82767. point2 = this._yline[1];
  82768. point2.x = yaxis.x * scaleLines;
  82769. point2.y = yaxis.y * scaleLines;
  82770. point2.z = yaxis.z * scaleLines;
  82771. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  82772. point2 = this._zline[1];
  82773. point2.x = zaxis.x * scaleLines;
  82774. point2.y = zaxis.y * scaleLines;
  82775. point2.z = zaxis.z * scaleLines;
  82776. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  82777. };
  82778. AxesViewer.prototype.dispose = function () {
  82779. if (this._xmesh) {
  82780. this._xmesh.dispose();
  82781. }
  82782. if (this._ymesh) {
  82783. this._ymesh.dispose();
  82784. }
  82785. if (this._zmesh) {
  82786. this._zmesh.dispose();
  82787. }
  82788. this._xmesh = null;
  82789. this._ymesh = null;
  82790. this._zmesh = null;
  82791. this.scene = null;
  82792. };
  82793. return AxesViewer;
  82794. }());
  82795. Debug.AxesViewer = AxesViewer;
  82796. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82797. })(BABYLON || (BABYLON = {}));
  82798. //# sourceMappingURL=babylon.axesViewer.js.map
  82799. "use strict";
  82800. var BABYLON;
  82801. (function (BABYLON) {
  82802. var Debug;
  82803. (function (Debug) {
  82804. /**
  82805. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  82806. */
  82807. var BoneAxesViewer = /** @class */ (function (_super) {
  82808. __extends(BoneAxesViewer, _super);
  82809. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  82810. if (scaleLines === void 0) { scaleLines = 1; }
  82811. var _this = _super.call(this, scene, scaleLines) || this;
  82812. _this.pos = BABYLON.Vector3.Zero();
  82813. _this.xaxis = BABYLON.Vector3.Zero();
  82814. _this.yaxis = BABYLON.Vector3.Zero();
  82815. _this.zaxis = BABYLON.Vector3.Zero();
  82816. _this.mesh = mesh;
  82817. _this.bone = bone;
  82818. return _this;
  82819. }
  82820. BoneAxesViewer.prototype.update = function () {
  82821. if (!this.mesh || !this.bone) {
  82822. return;
  82823. }
  82824. var bone = this.bone;
  82825. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  82826. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  82827. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  82828. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  82829. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  82830. };
  82831. BoneAxesViewer.prototype.dispose = function () {
  82832. if (this.mesh) {
  82833. this.mesh = null;
  82834. this.bone = null;
  82835. _super.prototype.dispose.call(this);
  82836. }
  82837. };
  82838. return BoneAxesViewer;
  82839. }(Debug.AxesViewer));
  82840. Debug.BoneAxesViewer = BoneAxesViewer;
  82841. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82842. })(BABYLON || (BABYLON = {}));
  82843. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  82844. "use strict";
  82845. var BABYLON;
  82846. (function (BABYLON) {
  82847. var RayHelper = /** @class */ (function () {
  82848. function RayHelper(ray) {
  82849. this.ray = ray;
  82850. }
  82851. RayHelper.CreateAndShow = function (ray, scene, color) {
  82852. var helper = new RayHelper(ray);
  82853. helper.show(scene, color);
  82854. return helper;
  82855. };
  82856. RayHelper.prototype.show = function (scene, color) {
  82857. if (!this._renderFunction && this.ray) {
  82858. var ray = this.ray;
  82859. this._renderFunction = this._render.bind(this);
  82860. this._scene = scene;
  82861. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  82862. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  82863. if (this._renderFunction) {
  82864. this._scene.registerBeforeRender(this._renderFunction);
  82865. }
  82866. }
  82867. if (color && this._renderLine) {
  82868. this._renderLine.color.copyFrom(color);
  82869. }
  82870. };
  82871. RayHelper.prototype.hide = function () {
  82872. if (this._renderFunction && this._scene) {
  82873. this._scene.unregisterBeforeRender(this._renderFunction);
  82874. this._scene = null;
  82875. this._renderFunction = null;
  82876. if (this._renderLine) {
  82877. this._renderLine.dispose();
  82878. this._renderLine = null;
  82879. }
  82880. this._renderPoints = [];
  82881. }
  82882. };
  82883. RayHelper.prototype._render = function () {
  82884. var ray = this.ray;
  82885. if (!ray) {
  82886. return;
  82887. }
  82888. var point = this._renderPoints[1];
  82889. var len = Math.min(ray.length, 1000000);
  82890. point.copyFrom(ray.direction);
  82891. point.scaleInPlace(len);
  82892. point.addInPlace(ray.origin);
  82893. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  82894. };
  82895. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  82896. this._attachedToMesh = mesh;
  82897. var ray = this.ray;
  82898. if (!ray) {
  82899. return;
  82900. }
  82901. if (!ray.direction) {
  82902. ray.direction = BABYLON.Vector3.Zero();
  82903. }
  82904. if (!ray.origin) {
  82905. ray.origin = BABYLON.Vector3.Zero();
  82906. }
  82907. if (length) {
  82908. ray.length = length;
  82909. }
  82910. if (!meshSpaceOrigin) {
  82911. meshSpaceOrigin = BABYLON.Vector3.Zero();
  82912. }
  82913. if (!meshSpaceDirection) {
  82914. // -1 so that this will work with Mesh.lookAt
  82915. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  82916. }
  82917. if (!this._meshSpaceDirection) {
  82918. this._meshSpaceDirection = meshSpaceDirection.clone();
  82919. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  82920. }
  82921. else {
  82922. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  82923. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  82924. }
  82925. if (!this._updateToMeshFunction) {
  82926. this._updateToMeshFunction = this._updateToMesh.bind(this);
  82927. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  82928. }
  82929. this._updateToMesh();
  82930. };
  82931. RayHelper.prototype.detachFromMesh = function () {
  82932. if (this._attachedToMesh) {
  82933. if (this._updateToMeshFunction) {
  82934. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  82935. }
  82936. this._attachedToMesh = null;
  82937. this._updateToMeshFunction = null;
  82938. }
  82939. };
  82940. RayHelper.prototype._updateToMesh = function () {
  82941. var ray = this.ray;
  82942. if (!this._attachedToMesh || !ray) {
  82943. return;
  82944. }
  82945. if (this._attachedToMesh._isDisposed) {
  82946. this.detachFromMesh();
  82947. return;
  82948. }
  82949. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  82950. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  82951. };
  82952. RayHelper.prototype.dispose = function () {
  82953. this.hide();
  82954. this.detachFromMesh();
  82955. this.ray = null;
  82956. };
  82957. return RayHelper;
  82958. }());
  82959. BABYLON.RayHelper = RayHelper;
  82960. })(BABYLON || (BABYLON = {}));
  82961. //# sourceMappingURL=babylon.rayHelper.js.map
  82962. "use strict";
  82963. var BABYLON;
  82964. (function (BABYLON) {
  82965. // load the inspector using require, if not present in the global namespace.
  82966. var DebugLayer = /** @class */ (function () {
  82967. function DebugLayer(scene) {
  82968. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  82969. this._scene = scene;
  82970. // load inspector using require, if it doesn't exist on the global namespace.
  82971. }
  82972. /** Creates the inspector window. */
  82973. DebugLayer.prototype._createInspector = function (config) {
  82974. if (config === void 0) { config = {}; }
  82975. var popup = config.popup || false;
  82976. var initialTab = config.initialTab || 0;
  82977. var parentElement = config.parentElement || null;
  82978. if (!this._inspector) {
  82979. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  82980. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  82981. } // else nothing to do,; instance is already existing
  82982. };
  82983. DebugLayer.prototype.isVisible = function () {
  82984. if (!this._inspector) {
  82985. return false;
  82986. }
  82987. return true;
  82988. };
  82989. DebugLayer.prototype.hide = function () {
  82990. if (this._inspector) {
  82991. try {
  82992. this._inspector.dispose();
  82993. }
  82994. catch (e) {
  82995. // If the inspector has been removed directly from the inspector tool
  82996. }
  82997. this._inspector = null;
  82998. }
  82999. };
  83000. DebugLayer.prototype.show = function (config) {
  83001. if (config === void 0) { config = {}; }
  83002. if (typeof this.BJSINSPECTOR == 'undefined') {
  83003. // Load inspector and add it to the DOM
  83004. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  83005. }
  83006. else {
  83007. // Otherwise creates the inspector
  83008. this._createInspector(config);
  83009. }
  83010. };
  83011. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  83012. return DebugLayer;
  83013. }());
  83014. BABYLON.DebugLayer = DebugLayer;
  83015. })(BABYLON || (BABYLON = {}));
  83016. //# sourceMappingURL=babylon.debugLayer.js.map
  83017. "use strict";
  83018. var BABYLON;
  83019. (function (BABYLON) {
  83020. var Debug;
  83021. (function (Debug) {
  83022. /**
  83023. * Used to show the physics impostor around the specific mesh.
  83024. */
  83025. var PhysicsViewer = /** @class */ (function () {
  83026. function PhysicsViewer(scene) {
  83027. this._impostors = [];
  83028. this._meshes = [];
  83029. this._numMeshes = 0;
  83030. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83031. var physicEngine = this._scene.getPhysicsEngine();
  83032. if (physicEngine) {
  83033. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  83034. }
  83035. }
  83036. PhysicsViewer.prototype._updateDebugMeshes = function () {
  83037. var plugin = this._physicsEnginePlugin;
  83038. for (var i = 0; i < this._numMeshes; i++) {
  83039. var impostor = this._impostors[i];
  83040. if (!impostor) {
  83041. continue;
  83042. }
  83043. if (impostor.isDisposed) {
  83044. this.hideImpostor(this._impostors[i--]);
  83045. }
  83046. else {
  83047. var mesh = this._meshes[i];
  83048. if (mesh && plugin) {
  83049. plugin.syncMeshWithImpostor(mesh, impostor);
  83050. }
  83051. }
  83052. }
  83053. };
  83054. PhysicsViewer.prototype.showImpostor = function (impostor) {
  83055. if (!this._scene) {
  83056. return;
  83057. }
  83058. for (var i = 0; i < this._numMeshes; i++) {
  83059. if (this._impostors[i] == impostor) {
  83060. return;
  83061. }
  83062. }
  83063. var debugMesh = this._getDebugMesh(impostor, this._scene);
  83064. if (debugMesh) {
  83065. this._impostors[this._numMeshes] = impostor;
  83066. this._meshes[this._numMeshes] = debugMesh;
  83067. if (this._numMeshes === 0) {
  83068. this._renderFunction = this._updateDebugMeshes.bind(this);
  83069. this._scene.registerBeforeRender(this._renderFunction);
  83070. }
  83071. this._numMeshes++;
  83072. }
  83073. };
  83074. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  83075. if (!impostor || !this._scene) {
  83076. return;
  83077. }
  83078. var removed = false;
  83079. for (var i = 0; i < this._numMeshes; i++) {
  83080. if (this._impostors[i] == impostor) {
  83081. var mesh = this._meshes[i];
  83082. if (!mesh) {
  83083. continue;
  83084. }
  83085. this._scene.removeMesh(mesh);
  83086. mesh.dispose();
  83087. this._numMeshes--;
  83088. if (this._numMeshes > 0) {
  83089. this._meshes[i] = this._meshes[this._numMeshes];
  83090. this._impostors[i] = this._impostors[this._numMeshes];
  83091. this._meshes[this._numMeshes] = null;
  83092. this._impostors[this._numMeshes] = null;
  83093. }
  83094. else {
  83095. this._meshes[0] = null;
  83096. this._impostors[0] = null;
  83097. }
  83098. removed = true;
  83099. break;
  83100. }
  83101. }
  83102. if (removed && this._numMeshes === 0) {
  83103. this._scene.unregisterBeforeRender(this._renderFunction);
  83104. }
  83105. };
  83106. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  83107. if (!this._debugMaterial) {
  83108. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83109. this._debugMaterial.wireframe = true;
  83110. }
  83111. return this._debugMaterial;
  83112. };
  83113. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83114. if (!this._debugBoxMesh) {
  83115. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83116. this._debugBoxMesh.renderingGroupId = 1;
  83117. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83118. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83119. scene.removeMesh(this._debugBoxMesh);
  83120. }
  83121. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83122. };
  83123. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83124. if (!this._debugSphereMesh) {
  83125. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83126. this._debugSphereMesh.renderingGroupId = 1;
  83127. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83128. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83129. scene.removeMesh(this._debugSphereMesh);
  83130. }
  83131. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83132. };
  83133. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83134. var mesh = null;
  83135. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83136. mesh = this._getDebugBoxMesh(scene);
  83137. impostor.getBoxSizeToRef(mesh.scaling);
  83138. }
  83139. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83140. mesh = this._getDebugSphereMesh(scene);
  83141. var radius = impostor.getRadius();
  83142. mesh.scaling.x = radius * 2;
  83143. mesh.scaling.y = radius * 2;
  83144. mesh.scaling.z = radius * 2;
  83145. }
  83146. return mesh;
  83147. };
  83148. PhysicsViewer.prototype.dispose = function () {
  83149. for (var i = 0; i < this._numMeshes; i++) {
  83150. this.hideImpostor(this._impostors[i]);
  83151. }
  83152. if (this._debugBoxMesh) {
  83153. this._debugBoxMesh.dispose();
  83154. }
  83155. if (this._debugSphereMesh) {
  83156. this._debugSphereMesh.dispose();
  83157. }
  83158. if (this._debugMaterial) {
  83159. this._debugMaterial.dispose();
  83160. }
  83161. this._impostors.length = 0;
  83162. this._scene = null;
  83163. this._physicsEnginePlugin = null;
  83164. };
  83165. return PhysicsViewer;
  83166. }());
  83167. Debug.PhysicsViewer = PhysicsViewer;
  83168. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83169. })(BABYLON || (BABYLON = {}));
  83170. //# sourceMappingURL=babylon.physicsViewer.js.map
  83171. "use strict";
  83172. var BABYLON;
  83173. (function (BABYLON) {
  83174. var BoundingBoxRenderer = /** @class */ (function () {
  83175. function BoundingBoxRenderer(scene) {
  83176. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83177. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83178. this.showBackLines = true;
  83179. this.renderList = new BABYLON.SmartArray(32);
  83180. this._vertexBuffers = {};
  83181. this._scene = scene;
  83182. }
  83183. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83184. if (this._colorShader) {
  83185. return;
  83186. }
  83187. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83188. attributes: [BABYLON.VertexBuffer.PositionKind],
  83189. uniforms: ["world", "viewProjection", "color"]
  83190. });
  83191. var engine = this._scene.getEngine();
  83192. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  83193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  83194. this._createIndexBuffer();
  83195. };
  83196. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  83197. var engine = this._scene.getEngine();
  83198. 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]);
  83199. };
  83200. BoundingBoxRenderer.prototype._rebuild = function () {
  83201. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83202. if (vb) {
  83203. vb._rebuild();
  83204. }
  83205. this._createIndexBuffer();
  83206. };
  83207. BoundingBoxRenderer.prototype.reset = function () {
  83208. this.renderList.reset();
  83209. };
  83210. BoundingBoxRenderer.prototype.render = function () {
  83211. if (this.renderList.length === 0) {
  83212. return;
  83213. }
  83214. this._prepareRessources();
  83215. if (!this._colorShader.isReady()) {
  83216. return;
  83217. }
  83218. var engine = this._scene.getEngine();
  83219. engine.setDepthWrite(false);
  83220. this._colorShader._preBind();
  83221. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  83222. var boundingBox = this.renderList.data[boundingBoxIndex];
  83223. var min = boundingBox.minimum;
  83224. var max = boundingBox.maximum;
  83225. var diff = max.subtract(min);
  83226. var median = min.add(diff.scale(0.5));
  83227. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83228. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83229. .multiply(boundingBox.getWorldMatrix());
  83230. // VBOs
  83231. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83232. if (this.showBackLines) {
  83233. // Back
  83234. engine.setDepthFunctionToGreaterOrEqual();
  83235. this._scene.resetCachedMaterial();
  83236. this._colorShader.setColor4("color", this.backColor.toColor4());
  83237. this._colorShader.bind(worldMatrix);
  83238. // Draw order
  83239. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83240. }
  83241. // Front
  83242. engine.setDepthFunctionToLess();
  83243. this._scene.resetCachedMaterial();
  83244. this._colorShader.setColor4("color", this.frontColor.toColor4());
  83245. this._colorShader.bind(worldMatrix);
  83246. // Draw order
  83247. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83248. }
  83249. this._colorShader.unbind();
  83250. engine.setDepthFunctionToLessOrEqual();
  83251. engine.setDepthWrite(true);
  83252. };
  83253. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  83254. this._prepareRessources();
  83255. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  83256. return;
  83257. }
  83258. var engine = this._scene.getEngine();
  83259. engine.setDepthWrite(false);
  83260. engine.setColorWrite(false);
  83261. this._colorShader._preBind();
  83262. var boundingBox = mesh._boundingInfo.boundingBox;
  83263. var min = boundingBox.minimum;
  83264. var max = boundingBox.maximum;
  83265. var diff = max.subtract(min);
  83266. var median = min.add(diff.scale(0.5));
  83267. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83268. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83269. .multiply(boundingBox.getWorldMatrix());
  83270. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83271. engine.setDepthFunctionToLess();
  83272. this._scene.resetCachedMaterial();
  83273. this._colorShader.bind(worldMatrix);
  83274. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83275. this._colorShader.unbind();
  83276. engine.setDepthFunctionToLessOrEqual();
  83277. engine.setDepthWrite(true);
  83278. engine.setColorWrite(true);
  83279. };
  83280. BoundingBoxRenderer.prototype.dispose = function () {
  83281. if (!this._colorShader) {
  83282. return;
  83283. }
  83284. this.renderList.dispose();
  83285. this._colorShader.dispose();
  83286. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83287. if (buffer) {
  83288. buffer.dispose();
  83289. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83290. }
  83291. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83292. };
  83293. return BoundingBoxRenderer;
  83294. }());
  83295. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  83296. })(BABYLON || (BABYLON = {}));
  83297. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  83298. "use strict";
  83299. var BABYLON;
  83300. (function (BABYLON) {
  83301. var MorphTarget = /** @class */ (function () {
  83302. function MorphTarget(name, influence) {
  83303. if (influence === void 0) { influence = 0; }
  83304. this.name = name;
  83305. this.animations = new Array();
  83306. this._positions = null;
  83307. this._normals = null;
  83308. this._tangents = null;
  83309. this.onInfluenceChanged = new BABYLON.Observable();
  83310. this.influence = influence;
  83311. }
  83312. Object.defineProperty(MorphTarget.prototype, "influence", {
  83313. get: function () {
  83314. return this._influence;
  83315. },
  83316. set: function (influence) {
  83317. if (this._influence === influence) {
  83318. return;
  83319. }
  83320. var previous = this._influence;
  83321. this._influence = influence;
  83322. if (this.onInfluenceChanged.hasObservers) {
  83323. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  83324. }
  83325. },
  83326. enumerable: true,
  83327. configurable: true
  83328. });
  83329. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  83330. get: function () {
  83331. return !!this._positions;
  83332. },
  83333. enumerable: true,
  83334. configurable: true
  83335. });
  83336. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  83337. get: function () {
  83338. return !!this._normals;
  83339. },
  83340. enumerable: true,
  83341. configurable: true
  83342. });
  83343. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  83344. get: function () {
  83345. return !!this._tangents;
  83346. },
  83347. enumerable: true,
  83348. configurable: true
  83349. });
  83350. MorphTarget.prototype.setPositions = function (data) {
  83351. this._positions = data;
  83352. };
  83353. MorphTarget.prototype.getPositions = function () {
  83354. return this._positions;
  83355. };
  83356. MorphTarget.prototype.setNormals = function (data) {
  83357. this._normals = data;
  83358. };
  83359. MorphTarget.prototype.getNormals = function () {
  83360. return this._normals;
  83361. };
  83362. MorphTarget.prototype.setTangents = function (data) {
  83363. this._tangents = data;
  83364. };
  83365. MorphTarget.prototype.getTangents = function () {
  83366. return this._tangents;
  83367. };
  83368. /**
  83369. * Serializes the current target into a Serialization object.
  83370. * Returns the serialized object.
  83371. */
  83372. MorphTarget.prototype.serialize = function () {
  83373. var serializationObject = {};
  83374. serializationObject.name = this.name;
  83375. serializationObject.influence = this.influence;
  83376. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  83377. if (this.hasNormals) {
  83378. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  83379. }
  83380. if (this.hasTangents) {
  83381. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  83382. }
  83383. // Animations
  83384. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  83385. return serializationObject;
  83386. };
  83387. // Statics
  83388. MorphTarget.Parse = function (serializationObject) {
  83389. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  83390. result.setPositions(serializationObject.positions);
  83391. if (serializationObject.normals) {
  83392. result.setNormals(serializationObject.normals);
  83393. }
  83394. if (serializationObject.tangents) {
  83395. result.setTangents(serializationObject.tangents);
  83396. }
  83397. // Animations
  83398. if (serializationObject.animations) {
  83399. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  83400. var parsedAnimation = serializationObject.animations[animationIndex];
  83401. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  83402. }
  83403. }
  83404. return result;
  83405. };
  83406. MorphTarget.FromMesh = function (mesh, name, influence) {
  83407. if (!name) {
  83408. name = mesh.name;
  83409. }
  83410. var result = new MorphTarget(name, influence);
  83411. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83413. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  83414. }
  83415. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  83416. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  83417. }
  83418. return result;
  83419. };
  83420. return MorphTarget;
  83421. }());
  83422. BABYLON.MorphTarget = MorphTarget;
  83423. })(BABYLON || (BABYLON = {}));
  83424. //# sourceMappingURL=babylon.morphTarget.js.map
  83425. "use strict";
  83426. var BABYLON;
  83427. (function (BABYLON) {
  83428. var MorphTargetManager = /** @class */ (function () {
  83429. function MorphTargetManager(scene) {
  83430. if (scene === void 0) { scene = null; }
  83431. this._targets = new Array();
  83432. this._targetObservable = new Array();
  83433. this._activeTargets = new BABYLON.SmartArray(16);
  83434. this._supportsNormals = false;
  83435. this._supportsTangents = false;
  83436. this._vertexCount = 0;
  83437. this._uniqueId = 0;
  83438. this._tempInfluences = new Array();
  83439. if (!scene) {
  83440. scene = BABYLON.Engine.LastCreatedScene;
  83441. }
  83442. this._scene = scene;
  83443. if (this._scene) {
  83444. this._scene.morphTargetManagers.push(this);
  83445. this._uniqueId = this._scene.getUniqueId();
  83446. }
  83447. }
  83448. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  83449. get: function () {
  83450. return this._uniqueId;
  83451. },
  83452. enumerable: true,
  83453. configurable: true
  83454. });
  83455. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  83456. get: function () {
  83457. return this._vertexCount;
  83458. },
  83459. enumerable: true,
  83460. configurable: true
  83461. });
  83462. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  83463. get: function () {
  83464. return this._supportsNormals;
  83465. },
  83466. enumerable: true,
  83467. configurable: true
  83468. });
  83469. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  83470. get: function () {
  83471. return this._supportsTangents;
  83472. },
  83473. enumerable: true,
  83474. configurable: true
  83475. });
  83476. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  83477. get: function () {
  83478. return this._targets.length;
  83479. },
  83480. enumerable: true,
  83481. configurable: true
  83482. });
  83483. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  83484. get: function () {
  83485. return this._activeTargets.length;
  83486. },
  83487. enumerable: true,
  83488. configurable: true
  83489. });
  83490. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  83491. get: function () {
  83492. return this._influences;
  83493. },
  83494. enumerable: true,
  83495. configurable: true
  83496. });
  83497. MorphTargetManager.prototype.getActiveTarget = function (index) {
  83498. return this._activeTargets.data[index];
  83499. };
  83500. MorphTargetManager.prototype.getTarget = function (index) {
  83501. return this._targets[index];
  83502. };
  83503. MorphTargetManager.prototype.addTarget = function (target) {
  83504. var _this = this;
  83505. this._targets.push(target);
  83506. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  83507. _this._syncActiveTargets(needUpdate);
  83508. }));
  83509. this._syncActiveTargets(true);
  83510. };
  83511. MorphTargetManager.prototype.removeTarget = function (target) {
  83512. var index = this._targets.indexOf(target);
  83513. if (index >= 0) {
  83514. this._targets.splice(index, 1);
  83515. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  83516. this._syncActiveTargets(true);
  83517. }
  83518. };
  83519. /**
  83520. * Serializes the current manager into a Serialization object.
  83521. * Returns the serialized object.
  83522. */
  83523. MorphTargetManager.prototype.serialize = function () {
  83524. var serializationObject = {};
  83525. serializationObject.id = this.uniqueId;
  83526. serializationObject.targets = [];
  83527. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83528. var target = _a[_i];
  83529. serializationObject.targets.push(target.serialize());
  83530. }
  83531. return serializationObject;
  83532. };
  83533. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  83534. var influenceCount = 0;
  83535. this._activeTargets.reset();
  83536. this._supportsNormals = true;
  83537. this._supportsTangents = true;
  83538. this._vertexCount = 0;
  83539. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83540. var target = _a[_i];
  83541. this._activeTargets.push(target);
  83542. this._tempInfluences[influenceCount++] = target.influence;
  83543. var positions = target.getPositions();
  83544. if (positions) {
  83545. this._supportsNormals = this._supportsNormals && target.hasNormals;
  83546. this._supportsTangents = this._supportsTangents && target.hasTangents;
  83547. var vertexCount = positions.length / 3;
  83548. if (this._vertexCount === 0) {
  83549. this._vertexCount = vertexCount;
  83550. }
  83551. else if (this._vertexCount !== vertexCount) {
  83552. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  83553. return;
  83554. }
  83555. }
  83556. }
  83557. if (!this._influences || this._influences.length !== influenceCount) {
  83558. this._influences = new Float32Array(influenceCount);
  83559. }
  83560. for (var index = 0; index < influenceCount; index++) {
  83561. this._influences[index] = this._tempInfluences[index];
  83562. }
  83563. if (needUpdate && this._scene) {
  83564. // Flag meshes as dirty to resync with the active targets
  83565. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  83566. var mesh = _c[_b];
  83567. if (mesh.morphTargetManager === this) {
  83568. mesh._syncGeometryWithMorphTargetManager();
  83569. }
  83570. }
  83571. }
  83572. };
  83573. // Statics
  83574. MorphTargetManager.Parse = function (serializationObject, scene) {
  83575. var result = new MorphTargetManager(scene);
  83576. result._uniqueId = serializationObject.id;
  83577. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  83578. var targetData = _a[_i];
  83579. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  83580. }
  83581. return result;
  83582. };
  83583. return MorphTargetManager;
  83584. }());
  83585. BABYLON.MorphTargetManager = MorphTargetManager;
  83586. })(BABYLON || (BABYLON = {}));
  83587. //# sourceMappingURL=babylon.morphTargetManager.js.map
  83588. "use strict";
  83589. var BABYLON;
  83590. (function (BABYLON) {
  83591. var Octree = /** @class */ (function () {
  83592. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  83593. if (maxDepth === void 0) { maxDepth = 2; }
  83594. this.maxDepth = maxDepth;
  83595. this.dynamicContent = new Array();
  83596. this._maxBlockCapacity = maxBlockCapacity || 64;
  83597. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  83598. this._creationFunc = creationFunc;
  83599. }
  83600. // Methods
  83601. Octree.prototype.update = function (worldMin, worldMax, entries) {
  83602. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  83603. };
  83604. Octree.prototype.addMesh = function (entry) {
  83605. for (var index = 0; index < this.blocks.length; index++) {
  83606. var block = this.blocks[index];
  83607. block.addEntry(entry);
  83608. }
  83609. };
  83610. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  83611. this._selectionContent.reset();
  83612. for (var index = 0; index < this.blocks.length; index++) {
  83613. var block = this.blocks[index];
  83614. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  83615. }
  83616. if (allowDuplicate) {
  83617. this._selectionContent.concat(this.dynamicContent);
  83618. }
  83619. else {
  83620. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83621. }
  83622. return this._selectionContent;
  83623. };
  83624. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  83625. this._selectionContent.reset();
  83626. for (var index = 0; index < this.blocks.length; index++) {
  83627. var block = this.blocks[index];
  83628. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  83629. }
  83630. if (allowDuplicate) {
  83631. this._selectionContent.concat(this.dynamicContent);
  83632. }
  83633. else {
  83634. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83635. }
  83636. return this._selectionContent;
  83637. };
  83638. Octree.prototype.intersectsRay = function (ray) {
  83639. this._selectionContent.reset();
  83640. for (var index = 0; index < this.blocks.length; index++) {
  83641. var block = this.blocks[index];
  83642. block.intersectsRay(ray, this._selectionContent);
  83643. }
  83644. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83645. return this._selectionContent;
  83646. };
  83647. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  83648. target.blocks = new Array();
  83649. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  83650. // Segmenting space
  83651. for (var x = 0; x < 2; x++) {
  83652. for (var y = 0; y < 2; y++) {
  83653. for (var z = 0; z < 2; z++) {
  83654. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  83655. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  83656. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  83657. block.addEntries(entries);
  83658. target.blocks.push(block);
  83659. }
  83660. }
  83661. }
  83662. };
  83663. Octree.CreationFuncForMeshes = function (entry, block) {
  83664. var boundingInfo = entry.getBoundingInfo();
  83665. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  83666. block.entries.push(entry);
  83667. }
  83668. };
  83669. Octree.CreationFuncForSubMeshes = function (entry, block) {
  83670. var boundingInfo = entry.getBoundingInfo();
  83671. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  83672. block.entries.push(entry);
  83673. }
  83674. };
  83675. return Octree;
  83676. }());
  83677. BABYLON.Octree = Octree;
  83678. })(BABYLON || (BABYLON = {}));
  83679. //# sourceMappingURL=babylon.octree.js.map
  83680. "use strict";
  83681. var BABYLON;
  83682. (function (BABYLON) {
  83683. var OctreeBlock = /** @class */ (function () {
  83684. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  83685. this.entries = new Array();
  83686. this._boundingVectors = new Array();
  83687. this._capacity = capacity;
  83688. this._depth = depth;
  83689. this._maxDepth = maxDepth;
  83690. this._creationFunc = creationFunc;
  83691. this._minPoint = minPoint;
  83692. this._maxPoint = maxPoint;
  83693. this._boundingVectors.push(minPoint.clone());
  83694. this._boundingVectors.push(maxPoint.clone());
  83695. this._boundingVectors.push(minPoint.clone());
  83696. this._boundingVectors[2].x = maxPoint.x;
  83697. this._boundingVectors.push(minPoint.clone());
  83698. this._boundingVectors[3].y = maxPoint.y;
  83699. this._boundingVectors.push(minPoint.clone());
  83700. this._boundingVectors[4].z = maxPoint.z;
  83701. this._boundingVectors.push(maxPoint.clone());
  83702. this._boundingVectors[5].z = minPoint.z;
  83703. this._boundingVectors.push(maxPoint.clone());
  83704. this._boundingVectors[6].x = minPoint.x;
  83705. this._boundingVectors.push(maxPoint.clone());
  83706. this._boundingVectors[7].y = minPoint.y;
  83707. }
  83708. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  83709. // Property
  83710. get: function () {
  83711. return this._capacity;
  83712. },
  83713. enumerable: true,
  83714. configurable: true
  83715. });
  83716. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  83717. get: function () {
  83718. return this._minPoint;
  83719. },
  83720. enumerable: true,
  83721. configurable: true
  83722. });
  83723. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  83724. get: function () {
  83725. return this._maxPoint;
  83726. },
  83727. enumerable: true,
  83728. configurable: true
  83729. });
  83730. // Methods
  83731. OctreeBlock.prototype.addEntry = function (entry) {
  83732. if (this.blocks) {
  83733. for (var index = 0; index < this.blocks.length; index++) {
  83734. var block = this.blocks[index];
  83735. block.addEntry(entry);
  83736. }
  83737. return;
  83738. }
  83739. this._creationFunc(entry, this);
  83740. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  83741. this.createInnerBlocks();
  83742. }
  83743. };
  83744. OctreeBlock.prototype.addEntries = function (entries) {
  83745. for (var index = 0; index < entries.length; index++) {
  83746. var mesh = entries[index];
  83747. this.addEntry(mesh);
  83748. }
  83749. };
  83750. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  83751. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  83752. if (this.blocks) {
  83753. for (var index = 0; index < this.blocks.length; index++) {
  83754. var block = this.blocks[index];
  83755. block.select(frustumPlanes, selection, allowDuplicate);
  83756. }
  83757. return;
  83758. }
  83759. if (allowDuplicate) {
  83760. selection.concat(this.entries);
  83761. }
  83762. else {
  83763. selection.concatWithNoDuplicate(this.entries);
  83764. }
  83765. }
  83766. };
  83767. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  83768. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  83769. if (this.blocks) {
  83770. for (var index = 0; index < this.blocks.length; index++) {
  83771. var block = this.blocks[index];
  83772. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  83773. }
  83774. return;
  83775. }
  83776. if (allowDuplicate) {
  83777. selection.concat(this.entries);
  83778. }
  83779. else {
  83780. selection.concatWithNoDuplicate(this.entries);
  83781. }
  83782. }
  83783. };
  83784. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  83785. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  83786. if (this.blocks) {
  83787. for (var index = 0; index < this.blocks.length; index++) {
  83788. var block = this.blocks[index];
  83789. block.intersectsRay(ray, selection);
  83790. }
  83791. return;
  83792. }
  83793. selection.concatWithNoDuplicate(this.entries);
  83794. }
  83795. };
  83796. OctreeBlock.prototype.createInnerBlocks = function () {
  83797. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  83798. };
  83799. return OctreeBlock;
  83800. }());
  83801. BABYLON.OctreeBlock = OctreeBlock;
  83802. })(BABYLON || (BABYLON = {}));
  83803. //# sourceMappingURL=babylon.octreeBlock.js.map
  83804. "use strict";
  83805. var BABYLON;
  83806. (function (BABYLON) {
  83807. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  83808. __extends(VRDistortionCorrectionPostProcess, _super);
  83809. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  83810. var _this = _super.call(this, name, "vrDistortionCorrection", [
  83811. 'LensCenter',
  83812. 'Scale',
  83813. 'ScaleIn',
  83814. 'HmdWarpParam'
  83815. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  83816. _this._isRightEye = isRightEye;
  83817. _this._distortionFactors = vrMetrics.distortionK;
  83818. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  83819. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  83820. _this.adaptScaleToCurrentViewport = true;
  83821. _this.onSizeChangedObservable.add(function () {
  83822. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  83823. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  83824. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  83825. });
  83826. _this.onApplyObservable.add(function (effect) {
  83827. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  83828. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  83829. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  83830. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  83831. });
  83832. return _this;
  83833. }
  83834. return VRDistortionCorrectionPostProcess;
  83835. }(BABYLON.PostProcess));
  83836. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  83837. })(BABYLON || (BABYLON = {}));
  83838. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  83839. "use strict";
  83840. var BABYLON;
  83841. (function (BABYLON) {
  83842. var AnaglyphPostProcess = /** @class */ (function (_super) {
  83843. __extends(AnaglyphPostProcess, _super);
  83844. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  83845. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  83846. _this._passedProcess = rigCameras[0]._rigPostProcess;
  83847. _this.onApplyObservable.add(function (effect) {
  83848. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  83849. });
  83850. return _this;
  83851. }
  83852. return AnaglyphPostProcess;
  83853. }(BABYLON.PostProcess));
  83854. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  83855. })(BABYLON || (BABYLON = {}));
  83856. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  83857. "use strict";
  83858. var BABYLON;
  83859. (function (BABYLON) {
  83860. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  83861. __extends(StereoscopicInterlacePostProcess, _super);
  83862. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  83863. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  83864. _this._passedProcess = rigCameras[0]._rigPostProcess;
  83865. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  83866. _this.onSizeChangedObservable.add(function () {
  83867. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  83868. });
  83869. _this.onApplyObservable.add(function (effect) {
  83870. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  83871. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  83872. });
  83873. return _this;
  83874. }
  83875. return StereoscopicInterlacePostProcess;
  83876. }(BABYLON.PostProcess));
  83877. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  83878. })(BABYLON || (BABYLON = {}));
  83879. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  83880. "use strict";
  83881. var BABYLON;
  83882. (function (BABYLON) {
  83883. /**
  83884. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  83885. * Screen rotation is taken into account.
  83886. */
  83887. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  83888. function FreeCameraDeviceOrientationInput() {
  83889. var _this = this;
  83890. this._screenOrientationAngle = 0;
  83891. this._screenQuaternion = new BABYLON.Quaternion();
  83892. this._alpha = 0;
  83893. this._beta = 0;
  83894. this._gamma = 0;
  83895. this._orientationChanged = function () {
  83896. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  83897. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  83898. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  83899. };
  83900. this._deviceOrientation = function (evt) {
  83901. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  83902. _this._beta = evt.beta !== null ? evt.beta : 0;
  83903. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  83904. };
  83905. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  83906. this._orientationChanged();
  83907. }
  83908. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  83909. get: function () {
  83910. return this._camera;
  83911. },
  83912. set: function (camera) {
  83913. this._camera = camera;
  83914. if (this._camera != null && !this._camera.rotationQuaternion) {
  83915. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  83916. }
  83917. },
  83918. enumerable: true,
  83919. configurable: true
  83920. });
  83921. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  83922. window.addEventListener("orientationchange", this._orientationChanged);
  83923. window.addEventListener("deviceorientation", this._deviceOrientation);
  83924. //In certain cases, the attach control is called AFTER orientation was changed,
  83925. //So this is needed.
  83926. this._orientationChanged();
  83927. };
  83928. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  83929. window.removeEventListener("orientationchange", this._orientationChanged);
  83930. window.removeEventListener("deviceorientation", this._deviceOrientation);
  83931. };
  83932. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  83933. //if no device orientation provided, don't update the rotation.
  83934. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  83935. if (!this._alpha)
  83936. return;
  83937. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  83938. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  83939. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  83940. //Mirror on XY Plane
  83941. this._camera.rotationQuaternion.z *= -1;
  83942. this._camera.rotationQuaternion.w *= -1;
  83943. };
  83944. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  83945. return "FreeCameraDeviceOrientationInput";
  83946. };
  83947. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  83948. return "deviceOrientation";
  83949. };
  83950. return FreeCameraDeviceOrientationInput;
  83951. }());
  83952. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  83953. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  83954. })(BABYLON || (BABYLON = {}));
  83955. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  83956. "use strict";
  83957. var BABYLON;
  83958. (function (BABYLON) {
  83959. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  83960. function ArcRotateCameraVRDeviceOrientationInput() {
  83961. this.alphaCorrection = 1;
  83962. this.betaCorrection = 1;
  83963. this.gammaCorrection = 1;
  83964. this._alpha = 0;
  83965. this._gamma = 0;
  83966. this._dirty = false;
  83967. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  83968. }
  83969. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  83970. this.camera.attachControl(element, noPreventDefault);
  83971. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  83972. };
  83973. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  83974. if (evt.alpha !== null) {
  83975. this._alpha = +evt.alpha | 0;
  83976. }
  83977. if (evt.gamma !== null) {
  83978. this._gamma = +evt.gamma | 0;
  83979. }
  83980. this._dirty = true;
  83981. };
  83982. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  83983. if (this._dirty) {
  83984. this._dirty = false;
  83985. if (this._gamma < 0) {
  83986. this._gamma = 180 + this._gamma;
  83987. }
  83988. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  83989. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  83990. }
  83991. };
  83992. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  83993. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  83994. };
  83995. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  83996. return "ArcRotateCameraVRDeviceOrientationInput";
  83997. };
  83998. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  83999. return "VRDeviceOrientation";
  84000. };
  84001. return ArcRotateCameraVRDeviceOrientationInput;
  84002. }());
  84003. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  84004. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  84005. })(BABYLON || (BABYLON = {}));
  84006. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  84007. "use strict";
  84008. var BABYLON;
  84009. (function (BABYLON) {
  84010. var VRCameraMetrics = /** @class */ (function () {
  84011. function VRCameraMetrics() {
  84012. this.compensateDistortion = true;
  84013. }
  84014. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  84015. get: function () {
  84016. return this.hResolution / (2 * this.vResolution);
  84017. },
  84018. enumerable: true,
  84019. configurable: true
  84020. });
  84021. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  84022. get: function () {
  84023. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  84024. },
  84025. enumerable: true,
  84026. configurable: true
  84027. });
  84028. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  84029. get: function () {
  84030. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84031. var h = (4 * meters) / this.hScreenSize;
  84032. return BABYLON.Matrix.Translation(h, 0, 0);
  84033. },
  84034. enumerable: true,
  84035. configurable: true
  84036. });
  84037. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  84038. get: function () {
  84039. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84040. var h = (4 * meters) / this.hScreenSize;
  84041. return BABYLON.Matrix.Translation(-h, 0, 0);
  84042. },
  84043. enumerable: true,
  84044. configurable: true
  84045. });
  84046. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  84047. get: function () {
  84048. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  84049. },
  84050. enumerable: true,
  84051. configurable: true
  84052. });
  84053. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  84054. get: function () {
  84055. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  84056. },
  84057. enumerable: true,
  84058. configurable: true
  84059. });
  84060. VRCameraMetrics.GetDefault = function () {
  84061. var result = new VRCameraMetrics();
  84062. result.hResolution = 1280;
  84063. result.vResolution = 800;
  84064. result.hScreenSize = 0.149759993;
  84065. result.vScreenSize = 0.0935999975;
  84066. result.vScreenCenter = 0.0467999987;
  84067. result.eyeToScreenDistance = 0.0410000011;
  84068. result.lensSeparationDistance = 0.0635000020;
  84069. result.interpupillaryDistance = 0.0640000030;
  84070. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  84071. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  84072. result.postProcessScaleFactor = 1.714605507808412;
  84073. result.lensCenterOffset = 0.151976421;
  84074. return result;
  84075. };
  84076. return VRCameraMetrics;
  84077. }());
  84078. BABYLON.VRCameraMetrics = VRCameraMetrics;
  84079. })(BABYLON || (BABYLON = {}));
  84080. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  84081. "use strict";
  84082. var BABYLON;
  84083. (function (BABYLON) {
  84084. /**
  84085. * This represents a WebVR camera.
  84086. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  84087. * @example http://doc.babylonjs.com/how_to/webvr_camera
  84088. */
  84089. var WebVRFreeCamera = /** @class */ (function (_super) {
  84090. __extends(WebVRFreeCamera, _super);
  84091. /**
  84092. * Instantiates a WebVRFreeCamera.
  84093. * @param name The name of the WebVRFreeCamera
  84094. * @param position The starting anchor position for the camera
  84095. * @param scene The scene the camera belongs to
  84096. * @param webVROptions a set of customizable options for the webVRCamera
  84097. */
  84098. function WebVRFreeCamera(name, position, scene, webVROptions) {
  84099. if (webVROptions === void 0) { webVROptions = {}; }
  84100. var _this = _super.call(this, name, position, scene) || this;
  84101. _this.webVROptions = webVROptions;
  84102. /**
  84103. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  84104. */
  84105. _this._vrDevice = null;
  84106. /**
  84107. * The rawPose of the vrDevice.
  84108. */
  84109. _this.rawPose = null;
  84110. _this._specsVersion = "1.1";
  84111. _this._attached = false;
  84112. _this._descendants = [];
  84113. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  84114. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  84115. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  84116. _this._standingMatrix = null;
  84117. /**
  84118. * Represents device position in babylon space.
  84119. */
  84120. _this.devicePosition = BABYLON.Vector3.Zero();
  84121. /**
  84122. * Represents device rotation in babylon space.
  84123. */
  84124. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  84125. /**
  84126. * The scale of the device to be used when translating from device space to babylon space.
  84127. */
  84128. _this.deviceScaleFactor = 1;
  84129. _this._deviceToWorld = BABYLON.Matrix.Identity();
  84130. _this._worldToDevice = BABYLON.Matrix.Identity();
  84131. /**
  84132. * References to the webVR controllers for the vrDevice.
  84133. */
  84134. _this.controllers = [];
  84135. /**
  84136. * Emits an event when a controller is attached.
  84137. */
  84138. _this.onControllersAttachedObservable = new BABYLON.Observable();
  84139. /**
  84140. * Emits an event when a controller's mesh has been loaded;
  84141. */
  84142. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84143. /**
  84144. * If the rig cameras be used as parent instead of this camera.
  84145. */
  84146. _this.rigParenting = true;
  84147. _this._defaultHeight = undefined;
  84148. _this._workingVector = BABYLON.Vector3.Zero();
  84149. _this._oneVector = BABYLON.Vector3.One();
  84150. _this._workingMatrix = BABYLON.Matrix.Identity();
  84151. _this._cache.position = BABYLON.Vector3.Zero();
  84152. if (webVROptions.defaultHeight) {
  84153. _this._defaultHeight = webVROptions.defaultHeight;
  84154. _this.position.y = _this._defaultHeight;
  84155. }
  84156. _this.minZ = 0.1;
  84157. //legacy support - the compensation boolean was removed.
  84158. if (arguments.length === 5) {
  84159. _this.webVROptions = arguments[4];
  84160. }
  84161. // default webVR options
  84162. if (_this.webVROptions.trackPosition == undefined) {
  84163. _this.webVROptions.trackPosition = true;
  84164. }
  84165. if (_this.webVROptions.controllerMeshes == undefined) {
  84166. _this.webVROptions.controllerMeshes = true;
  84167. }
  84168. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  84169. _this.webVROptions.defaultLightingOnControllers = true;
  84170. }
  84171. _this.rotationQuaternion = new BABYLON.Quaternion();
  84172. if (_this.webVROptions && _this.webVROptions.positionScale) {
  84173. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  84174. }
  84175. //enable VR
  84176. var engine = _this.getEngine();
  84177. _this._onVREnabled = function (success) { if (success) {
  84178. _this.initControllers();
  84179. } };
  84180. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  84181. engine.initWebVR().add(function (event) {
  84182. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  84183. return;
  84184. }
  84185. _this._vrDevice = event.vrDisplay;
  84186. //reset the rig parameters.
  84187. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  84188. if (_this._attached) {
  84189. _this.getEngine().enableVR();
  84190. }
  84191. });
  84192. if (typeof (VRFrameData) !== "undefined")
  84193. _this._frameData = new VRFrameData();
  84194. /**
  84195. * The idea behind the following lines:
  84196. * objects that have the camera as parent should actually have the rig cameras as a parent.
  84197. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  84198. * the second will not show it correctly.
  84199. *
  84200. * To solve this - each object that has the camera as parent will be added to a protected array.
  84201. * When the rig camera renders, it will take this array and set all of those to be its children.
  84202. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  84203. * Amazing!
  84204. */
  84205. scene.onBeforeCameraRenderObservable.add(function (camera) {
  84206. if (camera.parent === _this && _this.rigParenting) {
  84207. _this._descendants = _this.getDescendants(true, function (n) {
  84208. // don't take the cameras or the controllers!
  84209. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  84210. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  84211. return !isController && !isRigCamera;
  84212. });
  84213. _this._descendants.forEach(function (node) {
  84214. node.parent = camera;
  84215. });
  84216. }
  84217. });
  84218. scene.onAfterCameraRenderObservable.add(function (camera) {
  84219. if (camera.parent === _this && _this.rigParenting) {
  84220. _this._descendants.forEach(function (node) {
  84221. node.parent = _this;
  84222. });
  84223. }
  84224. });
  84225. return _this;
  84226. }
  84227. /**
  84228. * Gets the device distance from the ground in meters.
  84229. * @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.
  84230. */
  84231. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  84232. if (this._standingMatrix) {
  84233. // Add standing matrix offset to get real offset from ground in room
  84234. this._standingMatrix.getTranslationToRef(this._workingVector);
  84235. return this._deviceRoomPosition.y + this._workingVector.y;
  84236. }
  84237. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  84238. return this._defaultHeight || 0;
  84239. };
  84240. /**
  84241. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84242. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  84243. */
  84244. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  84245. var _this = this;
  84246. if (callback === void 0) { callback = function (bool) { }; }
  84247. // Use standing matrix if available
  84248. this.getEngine().initWebVRAsync().then(function (result) {
  84249. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  84250. callback(false);
  84251. }
  84252. else {
  84253. _this._standingMatrix = new BABYLON.Matrix();
  84254. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  84255. if (!_this.getScene().useRightHandedSystem) {
  84256. [2, 6, 8, 9, 14].forEach(function (num) {
  84257. if (_this._standingMatrix) {
  84258. _this._standingMatrix.m[num] *= -1;
  84259. }
  84260. });
  84261. }
  84262. callback(true);
  84263. }
  84264. });
  84265. };
  84266. /**
  84267. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84268. * @returns A promise with a boolean set to if the standing matrix is supported.
  84269. */
  84270. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  84271. var _this = this;
  84272. return new Promise(function (res, rej) {
  84273. _this.useStandingMatrix(function (supported) {
  84274. res(supported);
  84275. });
  84276. });
  84277. };
  84278. /**
  84279. * Disposes the camera
  84280. */
  84281. WebVRFreeCamera.prototype.dispose = function () {
  84282. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  84283. _super.prototype.dispose.call(this);
  84284. };
  84285. /**
  84286. * Gets a vrController by name.
  84287. * @param name The name of the controller to retreive
  84288. * @returns the controller matching the name specified or null if not found
  84289. */
  84290. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  84291. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  84292. var gp = _a[_i];
  84293. if (gp.hand === name) {
  84294. return gp;
  84295. }
  84296. }
  84297. return null;
  84298. };
  84299. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  84300. /**
  84301. * The controller corrisponding to the users left hand.
  84302. */
  84303. get: function () {
  84304. if (!this._leftController) {
  84305. this._leftController = this.getControllerByName("left");
  84306. }
  84307. return this._leftController;
  84308. },
  84309. enumerable: true,
  84310. configurable: true
  84311. });
  84312. ;
  84313. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  84314. /**
  84315. * The controller corrisponding to the users right hand.
  84316. */
  84317. get: function () {
  84318. if (!this._rightController) {
  84319. this._rightController = this.getControllerByName("right");
  84320. }
  84321. return this._rightController;
  84322. },
  84323. enumerable: true,
  84324. configurable: true
  84325. });
  84326. ;
  84327. /**
  84328. * Casts a ray forward from the vrCamera's gaze.
  84329. * @param length Length of the ray (default: 100)
  84330. * @returns the ray corrisponding to the gaze
  84331. */
  84332. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  84333. if (length === void 0) { length = 100; }
  84334. if (this.leftCamera) {
  84335. // Use left eye to avoid computation to compute center on every call
  84336. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  84337. }
  84338. else {
  84339. return _super.prototype.getForwardRay.call(this, length);
  84340. }
  84341. };
  84342. /**
  84343. * Updates the camera based on device's frame data
  84344. */
  84345. WebVRFreeCamera.prototype._checkInputs = function () {
  84346. if (this._vrDevice && this._vrDevice.isPresenting) {
  84347. this._vrDevice.getFrameData(this._frameData);
  84348. this.updateFromDevice(this._frameData.pose);
  84349. }
  84350. _super.prototype._checkInputs.call(this);
  84351. };
  84352. /**
  84353. * Updates the poseControlled values based on the input device pose.
  84354. * @param poseData Pose coming from the device
  84355. */
  84356. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  84357. if (poseData && poseData.orientation) {
  84358. this.rawPose = poseData;
  84359. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  84360. if (this.getScene().useRightHandedSystem) {
  84361. this._deviceRoomRotationQuaternion.z *= -1;
  84362. this._deviceRoomRotationQuaternion.w *= -1;
  84363. }
  84364. if (this.webVROptions.trackPosition && this.rawPose.position) {
  84365. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  84366. if (this.getScene().useRightHandedSystem) {
  84367. this._deviceRoomPosition.z *= -1;
  84368. }
  84369. }
  84370. }
  84371. };
  84372. /**
  84373. * WebVR's attach control will start broadcasting frames to the device.
  84374. * Note that in certain browsers (chrome for example) this function must be called
  84375. * within a user-interaction callback. Example:
  84376. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  84377. *
  84378. * @param element html element to attach the vrDevice to
  84379. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  84380. */
  84381. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  84382. _super.prototype.attachControl.call(this, element, noPreventDefault);
  84383. this._attached = true;
  84384. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  84385. if (this._vrDevice) {
  84386. this.getEngine().enableVR();
  84387. }
  84388. };
  84389. /**
  84390. * Detaches the camera from the html element and disables VR
  84391. *
  84392. * @param element html element to detach from
  84393. */
  84394. WebVRFreeCamera.prototype.detachControl = function (element) {
  84395. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  84396. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  84397. _super.prototype.detachControl.call(this, element);
  84398. this._attached = false;
  84399. this.getEngine().disableVR();
  84400. };
  84401. /**
  84402. * @returns the name of this class
  84403. */
  84404. WebVRFreeCamera.prototype.getClassName = function () {
  84405. return "WebVRFreeCamera";
  84406. };
  84407. /**
  84408. * Calls resetPose on the vrDisplay
  84409. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  84410. */
  84411. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  84412. //uses the vrDisplay's "resetPose()".
  84413. //pitch and roll won't be affected.
  84414. this._vrDevice.resetPose();
  84415. };
  84416. /**
  84417. * Updates the rig cameras (left and right eye)
  84418. */
  84419. WebVRFreeCamera.prototype._updateRigCameras = function () {
  84420. var camLeft = this._rigCameras[0];
  84421. var camRight = this._rigCameras[1];
  84422. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84423. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84424. camLeft.position.copyFrom(this._deviceRoomPosition);
  84425. camRight.position.copyFrom(this._deviceRoomPosition);
  84426. };
  84427. /**
  84428. * Updates the cached values of the camera
  84429. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  84430. */
  84431. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  84432. var _this = this;
  84433. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  84434. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  84435. if (!this.updateCacheCalled) {
  84436. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  84437. this.updateCacheCalled = true;
  84438. this.update();
  84439. }
  84440. // Set working vector to the device position in room space rotated by the new rotation
  84441. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  84442. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  84443. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  84444. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  84445. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  84446. // Add translation from anchor position
  84447. this._deviceToWorld.getTranslationToRef(this._workingVector);
  84448. this._workingVector.addInPlace(this.position);
  84449. this._workingVector.subtractInPlace(this._cache.position);
  84450. this._deviceToWorld.setTranslation(this._workingVector);
  84451. // Set an inverted matrix to be used when updating the camera
  84452. this._deviceToWorld.invertToRef(this._worldToDevice);
  84453. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  84454. this.controllers.forEach(function (controller) {
  84455. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  84456. controller.update();
  84457. });
  84458. }
  84459. if (!ignoreParentClass) {
  84460. _super.prototype._updateCache.call(this);
  84461. }
  84462. this.updateCacheCalled = false;
  84463. };
  84464. /**
  84465. * Updates the current device position and rotation in the babylon world
  84466. */
  84467. WebVRFreeCamera.prototype.update = function () {
  84468. // Get current device position in babylon world
  84469. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  84470. // Get current device rotation in babylon world
  84471. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  84472. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  84473. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  84474. _super.prototype.update.call(this);
  84475. };
  84476. /**
  84477. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  84478. * @returns an identity matrix
  84479. */
  84480. WebVRFreeCamera.prototype._getViewMatrix = function () {
  84481. return BABYLON.Matrix.Identity();
  84482. };
  84483. /**
  84484. * This function is called by the two RIG cameras.
  84485. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  84486. */
  84487. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  84488. var _this = this;
  84489. // Update the parent camera prior to using a child camera to avoid desynchronization
  84490. var parentCamera = this._cameraRigParams["parentCamera"];
  84491. parentCamera._updateCache();
  84492. //WebVR 1.1
  84493. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  84494. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  84495. if (!this.getScene().useRightHandedSystem) {
  84496. [2, 6, 8, 9, 14].forEach(function (num) {
  84497. _this._webvrViewMatrix.m[num] *= -1;
  84498. });
  84499. }
  84500. // update the camera rotation matrix
  84501. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  84502. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  84503. // Computing target and final matrix
  84504. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  84505. // should the view matrix be updated with scale and position offset?
  84506. if (parentCamera.deviceScaleFactor !== 1) {
  84507. this._webvrViewMatrix.invert();
  84508. // scale the position, if set
  84509. if (parentCamera.deviceScaleFactor) {
  84510. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  84511. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  84512. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  84513. }
  84514. this._webvrViewMatrix.invert();
  84515. }
  84516. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  84517. return this._webvrViewMatrix;
  84518. };
  84519. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  84520. var _this = this;
  84521. var parentCamera = this.parent;
  84522. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  84523. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  84524. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  84525. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  84526. //babylon compatible matrix
  84527. if (!this.getScene().useRightHandedSystem) {
  84528. [8, 9, 10, 11].forEach(function (num) {
  84529. _this._projectionMatrix.m[num] *= -1;
  84530. });
  84531. }
  84532. return this._projectionMatrix;
  84533. };
  84534. /**
  84535. * Initializes the controllers and their meshes
  84536. */
  84537. WebVRFreeCamera.prototype.initControllers = function () {
  84538. var _this = this;
  84539. this.controllers = [];
  84540. var manager = this.getScene().gamepadManager;
  84541. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  84542. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84543. var webVrController = gamepad;
  84544. if (webVrController.defaultModel) {
  84545. webVrController.defaultModel.setEnabled(false);
  84546. }
  84547. if (webVrController.hand === "right") {
  84548. _this._rightController = null;
  84549. }
  84550. if (webVrController.hand === "left") {
  84551. _this._leftController = null;
  84552. }
  84553. var controllerIndex = _this.controllers.indexOf(webVrController);
  84554. if (controllerIndex !== -1) {
  84555. _this.controllers.splice(controllerIndex, 1);
  84556. }
  84557. }
  84558. });
  84559. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  84560. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84561. var webVrController_1 = gamepad;
  84562. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  84563. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  84564. if (_this.webVROptions.controllerMeshes) {
  84565. if (webVrController_1.defaultModel) {
  84566. webVrController_1.defaultModel.setEnabled(true);
  84567. }
  84568. else {
  84569. // Load the meshes
  84570. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  84571. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  84572. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  84573. if (_this.webVROptions.defaultLightingOnControllers) {
  84574. if (!_this._lightOnControllers) {
  84575. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  84576. }
  84577. var activateLightOnSubMeshes_1 = function (mesh, light) {
  84578. var children = mesh.getChildren();
  84579. if (children.length !== 0) {
  84580. children.forEach(function (mesh) {
  84581. light.includedOnlyMeshes.push(mesh);
  84582. activateLightOnSubMeshes_1(mesh, light);
  84583. });
  84584. }
  84585. };
  84586. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  84587. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  84588. }
  84589. });
  84590. }
  84591. }
  84592. webVrController_1.attachToPoseControlledCamera(_this);
  84593. // since this is async - sanity check. Is the controller already stored?
  84594. if (_this.controllers.indexOf(webVrController_1) === -1) {
  84595. //add to the controllers array
  84596. _this.controllers.push(webVrController_1);
  84597. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  84598. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  84599. // So we're overriding setting left & right manually to be sure
  84600. var firstViveWandDetected = false;
  84601. for (var i = 0; i < _this.controllers.length; i++) {
  84602. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  84603. if (!firstViveWandDetected) {
  84604. firstViveWandDetected = true;
  84605. _this.controllers[i].hand = "left";
  84606. }
  84607. else {
  84608. _this.controllers[i].hand = "right";
  84609. }
  84610. }
  84611. }
  84612. //did we find enough controllers? Great! let the developer know.
  84613. if (_this.controllers.length >= 2) {
  84614. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  84615. }
  84616. }
  84617. }
  84618. });
  84619. };
  84620. return WebVRFreeCamera;
  84621. }(BABYLON.FreeCamera));
  84622. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  84623. })(BABYLON || (BABYLON = {}));
  84624. //# sourceMappingURL=babylon.webVRCamera.js.map
  84625. "use strict";
  84626. var BABYLON;
  84627. (function (BABYLON) {
  84628. // We're mainly based on the logic defined into the FreeCamera code
  84629. /**
  84630. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  84631. * being tilted forward or back and left or right.
  84632. */
  84633. var DeviceOrientationCamera = /** @class */ (function (_super) {
  84634. __extends(DeviceOrientationCamera, _super);
  84635. /**
  84636. * Creates a new device orientation camera
  84637. * @param name The name of the camera
  84638. * @param position The start position camera
  84639. * @param scene The scene the camera belongs to
  84640. */
  84641. function DeviceOrientationCamera(name, position, scene) {
  84642. var _this = _super.call(this, name, position, scene) || this;
  84643. _this._quaternionCache = new BABYLON.Quaternion();
  84644. _this.inputs.addDeviceOrientation();
  84645. return _this;
  84646. }
  84647. /**
  84648. * Gets the current instance class name ("DeviceOrientationCamera").
  84649. * This helps avoiding instanceof at run time.
  84650. * @returns the class name
  84651. */
  84652. DeviceOrientationCamera.prototype.getClassName = function () {
  84653. return "DeviceOrientationCamera";
  84654. };
  84655. /**
  84656. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  84657. */
  84658. DeviceOrientationCamera.prototype._checkInputs = function () {
  84659. _super.prototype._checkInputs.call(this);
  84660. this._quaternionCache.copyFrom(this.rotationQuaternion);
  84661. if (this._initialQuaternion) {
  84662. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  84663. }
  84664. };
  84665. /**
  84666. * Reset the camera to its default orientation on the specified axis only.
  84667. * @param axis The axis to reset
  84668. */
  84669. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  84670. var _this = this;
  84671. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  84672. //can only work if this camera has a rotation quaternion already.
  84673. if (!this.rotationQuaternion)
  84674. return;
  84675. if (!this._initialQuaternion) {
  84676. this._initialQuaternion = new BABYLON.Quaternion();
  84677. }
  84678. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  84679. ['x', 'y', 'z'].forEach(function (axisName) {
  84680. if (!axis[axisName]) {
  84681. _this._initialQuaternion[axisName] = 0;
  84682. }
  84683. else {
  84684. _this._initialQuaternion[axisName] *= -1;
  84685. }
  84686. });
  84687. this._initialQuaternion.normalize();
  84688. //force rotation update
  84689. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  84690. };
  84691. return DeviceOrientationCamera;
  84692. }(BABYLON.FreeCamera));
  84693. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  84694. })(BABYLON || (BABYLON = {}));
  84695. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  84696. "use strict";
  84697. var BABYLON;
  84698. (function (BABYLON) {
  84699. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  84700. __extends(VRDeviceOrientationFreeCamera, _super);
  84701. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  84702. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84703. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84704. var _this = _super.call(this, name, position, scene) || this;
  84705. vrCameraMetrics.compensateDistortion = compensateDistortion;
  84706. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  84707. return _this;
  84708. }
  84709. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  84710. return "VRDeviceOrientationFreeCamera";
  84711. };
  84712. return VRDeviceOrientationFreeCamera;
  84713. }(BABYLON.DeviceOrientationCamera));
  84714. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  84715. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  84716. __extends(VRDeviceOrientationGamepadCamera, _super);
  84717. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  84718. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84719. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84720. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  84721. _this.inputs.addGamepad();
  84722. return _this;
  84723. }
  84724. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  84725. return "VRDeviceOrientationGamepadCamera";
  84726. };
  84727. return VRDeviceOrientationGamepadCamera;
  84728. }(VRDeviceOrientationFreeCamera));
  84729. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  84730. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  84731. __extends(VRDeviceOrientationArcRotateCamera, _super);
  84732. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  84733. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84734. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84735. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84736. vrCameraMetrics.compensateDistortion = compensateDistortion;
  84737. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  84738. _this.inputs.addVRDeviceOrientation();
  84739. return _this;
  84740. }
  84741. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  84742. return "VRDeviceOrientationArcRotateCamera";
  84743. };
  84744. return VRDeviceOrientationArcRotateCamera;
  84745. }(BABYLON.ArcRotateCamera));
  84746. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  84747. })(BABYLON || (BABYLON = {}));
  84748. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  84749. "use strict";
  84750. var BABYLON;
  84751. (function (BABYLON) {
  84752. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  84753. __extends(AnaglyphFreeCamera, _super);
  84754. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  84755. var _this = _super.call(this, name, position, scene) || this;
  84756. _this.interaxialDistance = interaxialDistance;
  84757. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84758. return _this;
  84759. }
  84760. AnaglyphFreeCamera.prototype.getClassName = function () {
  84761. return "AnaglyphFreeCamera";
  84762. };
  84763. return AnaglyphFreeCamera;
  84764. }(BABYLON.FreeCamera));
  84765. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  84766. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  84767. __extends(AnaglyphArcRotateCamera, _super);
  84768. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  84769. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84770. _this.interaxialDistance = interaxialDistance;
  84771. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84772. return _this;
  84773. }
  84774. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  84775. return "AnaglyphArcRotateCamera";
  84776. };
  84777. return AnaglyphArcRotateCamera;
  84778. }(BABYLON.ArcRotateCamera));
  84779. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  84780. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  84781. __extends(AnaglyphGamepadCamera, _super);
  84782. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  84783. var _this = _super.call(this, name, position, scene) || this;
  84784. _this.interaxialDistance = interaxialDistance;
  84785. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84786. return _this;
  84787. }
  84788. AnaglyphGamepadCamera.prototype.getClassName = function () {
  84789. return "AnaglyphGamepadCamera";
  84790. };
  84791. return AnaglyphGamepadCamera;
  84792. }(BABYLON.GamepadCamera));
  84793. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  84794. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  84795. __extends(AnaglyphUniversalCamera, _super);
  84796. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  84797. var _this = _super.call(this, name, position, scene) || this;
  84798. _this.interaxialDistance = interaxialDistance;
  84799. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84800. return _this;
  84801. }
  84802. AnaglyphUniversalCamera.prototype.getClassName = function () {
  84803. return "AnaglyphUniversalCamera";
  84804. };
  84805. return AnaglyphUniversalCamera;
  84806. }(BABYLON.UniversalCamera));
  84807. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  84808. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  84809. __extends(StereoscopicFreeCamera, _super);
  84810. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84811. var _this = _super.call(this, name, position, scene) || this;
  84812. _this.interaxialDistance = interaxialDistance;
  84813. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84814. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84815. return _this;
  84816. }
  84817. StereoscopicFreeCamera.prototype.getClassName = function () {
  84818. return "StereoscopicFreeCamera";
  84819. };
  84820. return StereoscopicFreeCamera;
  84821. }(BABYLON.FreeCamera));
  84822. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  84823. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  84824. __extends(StereoscopicArcRotateCamera, _super);
  84825. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  84826. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84827. _this.interaxialDistance = interaxialDistance;
  84828. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84829. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84830. return _this;
  84831. }
  84832. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  84833. return "StereoscopicArcRotateCamera";
  84834. };
  84835. return StereoscopicArcRotateCamera;
  84836. }(BABYLON.ArcRotateCamera));
  84837. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  84838. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  84839. __extends(StereoscopicGamepadCamera, _super);
  84840. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84841. var _this = _super.call(this, name, position, scene) || this;
  84842. _this.interaxialDistance = interaxialDistance;
  84843. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84844. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84845. return _this;
  84846. }
  84847. StereoscopicGamepadCamera.prototype.getClassName = function () {
  84848. return "StereoscopicGamepadCamera";
  84849. };
  84850. return StereoscopicGamepadCamera;
  84851. }(BABYLON.GamepadCamera));
  84852. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  84853. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  84854. __extends(StereoscopicUniversalCamera, _super);
  84855. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84856. var _this = _super.call(this, name, position, scene) || this;
  84857. _this.interaxialDistance = interaxialDistance;
  84858. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84859. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84860. return _this;
  84861. }
  84862. StereoscopicUniversalCamera.prototype.getClassName = function () {
  84863. return "StereoscopicUniversalCamera";
  84864. };
  84865. return StereoscopicUniversalCamera;
  84866. }(BABYLON.UniversalCamera));
  84867. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  84868. })(BABYLON || (BABYLON = {}));
  84869. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  84870. "use strict";
  84871. var BABYLON;
  84872. (function (BABYLON) {
  84873. var VRExperienceHelperGazer = /** @class */ (function () {
  84874. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  84875. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  84876. this.scene = scene;
  84877. this._pointerDownOnMeshAsked = false;
  84878. this._isActionableMesh = false;
  84879. this._teleportationRequestInitiated = false;
  84880. this._teleportationBackRequestInitiated = false;
  84881. this._dpadPressed = true;
  84882. this._activePointer = false;
  84883. this._id = VRExperienceHelperGazer._idCounter++;
  84884. // Gaze tracker
  84885. if (!gazeTrackerToClone) {
  84886. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  84887. this._gazeTracker.bakeCurrentTransformIntoVertices();
  84888. this._gazeTracker.isPickable = false;
  84889. this._gazeTracker.isVisible = false;
  84890. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  84891. targetMat.specularColor = BABYLON.Color3.Black();
  84892. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  84893. targetMat.backFaceCulling = false;
  84894. this._gazeTracker.material = targetMat;
  84895. }
  84896. else {
  84897. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  84898. }
  84899. }
  84900. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  84901. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  84902. };
  84903. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  84904. this._pointerDownOnMeshAsked = true;
  84905. if (this._currentMeshSelected && this._currentHit) {
  84906. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  84907. }
  84908. };
  84909. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  84910. if (this._currentMeshSelected && this._currentHit) {
  84911. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  84912. }
  84913. this._pointerDownOnMeshAsked = false;
  84914. };
  84915. VRExperienceHelperGazer.prototype._activatePointer = function () {
  84916. this._activePointer = true;
  84917. };
  84918. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  84919. this._activePointer = false;
  84920. };
  84921. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  84922. };
  84923. VRExperienceHelperGazer.prototype.dispose = function () {
  84924. this._interactionsEnabled = false;
  84925. this._teleportationEnabled = false;
  84926. };
  84927. VRExperienceHelperGazer._idCounter = 0;
  84928. return VRExperienceHelperGazer;
  84929. }());
  84930. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  84931. __extends(VRExperienceHelperControllerGazer, _super);
  84932. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  84933. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  84934. _this.webVRController = webVRController;
  84935. // Laser pointer
  84936. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  84937. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  84938. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  84939. laserPointerMaterial.alpha = 0.6;
  84940. _this._laserPointer.material = laserPointerMaterial;
  84941. _this._laserPointer.rotation.x = Math.PI / 2;
  84942. _this._laserPointer.position.z = -0.5;
  84943. _this._laserPointer.isVisible = false;
  84944. if (!webVRController.mesh) {
  84945. // Create an empty mesh that is used prior to loading the high quality model
  84946. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  84947. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  84948. preloadPointerPose.rotation.x = -0.7;
  84949. preloadMesh.addChild(preloadPointerPose);
  84950. webVRController.attachToMesh(preloadMesh);
  84951. }
  84952. _this._setLaserPointerParent(webVRController.mesh);
  84953. return _this;
  84954. }
  84955. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  84956. return this.webVRController.getForwardRay(length);
  84957. };
  84958. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  84959. _super.prototype._activatePointer.call(this);
  84960. this._laserPointer.isVisible = true;
  84961. };
  84962. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  84963. _super.prototype._deactivatePointer.call(this);
  84964. this._laserPointer.isVisible = false;
  84965. };
  84966. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  84967. this._laserPointer.material.emissiveColor = color;
  84968. };
  84969. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  84970. var makeNotPick = function (root) {
  84971. root.name += " laserPointer";
  84972. root.getChildMeshes().forEach(function (c) {
  84973. makeNotPick(c);
  84974. });
  84975. };
  84976. makeNotPick(mesh);
  84977. var childMeshes = mesh.getChildMeshes();
  84978. this.webVRController._pointingPoseNode = null;
  84979. for (var i = 0; i < childMeshes.length; i++) {
  84980. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  84981. mesh = childMeshes[i];
  84982. this.webVRController._pointingPoseNode = mesh;
  84983. break;
  84984. }
  84985. }
  84986. this._laserPointer.parent = mesh;
  84987. };
  84988. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  84989. this._laserPointer.scaling.y = distance;
  84990. this._laserPointer.position.z = -distance / 2;
  84991. };
  84992. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  84993. _super.prototype.dispose.call(this);
  84994. this._laserPointer.dispose();
  84995. };
  84996. return VRExperienceHelperControllerGazer;
  84997. }(VRExperienceHelperGazer));
  84998. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  84999. __extends(VRExperienceHelperCameraGazer, _super);
  85000. function VRExperienceHelperCameraGazer(getCamera, scene) {
  85001. var _this = _super.call(this, scene) || this;
  85002. _this.getCamera = getCamera;
  85003. return _this;
  85004. }
  85005. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  85006. var camera = this.getCamera();
  85007. if (camera) {
  85008. return camera.getForwardRay(length);
  85009. }
  85010. else {
  85011. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  85012. }
  85013. };
  85014. return VRExperienceHelperCameraGazer;
  85015. }(VRExperienceHelperGazer));
  85016. /**
  85017. * Helps to quickly add VR support to an existing scene.
  85018. * See http://doc.babylonjs.com/how_to/webvr_helper
  85019. */
  85020. var VRExperienceHelper = /** @class */ (function () {
  85021. /**
  85022. * Instantiates a VRExperienceHelper.
  85023. * Helps to quickly add VR support to an existing scene.
  85024. * @param scene The scene the VRExperienceHelper belongs to.
  85025. * @param webVROptions Options to modify the vr experience helper's behavior.
  85026. */
  85027. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  85028. if (webVROptions === void 0) { webVROptions = {}; }
  85029. var _this = this;
  85030. this.webVROptions = webVROptions;
  85031. // Can the system support WebVR, even if a headset isn't plugged in?
  85032. this._webVRsupported = false;
  85033. // If WebVR is supported, is a headset plugged in and are we ready to present?
  85034. this._webVRready = false;
  85035. // Are we waiting for the requestPresent callback to complete?
  85036. this._webVRrequesting = false;
  85037. // Are we presenting to the headset right now?
  85038. this._webVRpresenting = false;
  85039. // Are we presenting in the fullscreen fallback?
  85040. this._fullscreenVRpresenting = false;
  85041. /**
  85042. * Observable raised when entering VR.
  85043. */
  85044. this.onEnteringVRObservable = new BABYLON.Observable();
  85045. /**
  85046. * Observable raised when exiting VR.
  85047. */
  85048. this.onExitingVRObservable = new BABYLON.Observable();
  85049. /**
  85050. * Observable raised when controller mesh is loaded.
  85051. */
  85052. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85053. this._useCustomVRButton = false;
  85054. this._teleportationRequested = false;
  85055. this._teleportActive = false;
  85056. this._floorMeshesCollection = [];
  85057. this._rotationAllowed = true;
  85058. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  85059. this._rotationRightAsked = false;
  85060. this._rotationLeftAsked = false;
  85061. this._isDefaultTeleportationTarget = true;
  85062. this._teleportationFillColor = "#444444";
  85063. this._teleportationBorderColor = "#FFFFFF";
  85064. this._rotationAngle = 0;
  85065. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  85066. this._padSensibilityUp = 0.65;
  85067. this._padSensibilityDown = 0.35;
  85068. this.leftController = null;
  85069. this.rightController = null;
  85070. /**
  85071. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  85072. */
  85073. this.onNewMeshSelected = new BABYLON.Observable();
  85074. /**
  85075. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  85076. */
  85077. this.onNewMeshPicked = new BABYLON.Observable();
  85078. /**
  85079. * Observable raised before camera teleportation
  85080. */
  85081. this.onBeforeCameraTeleport = new BABYLON.Observable();
  85082. /**
  85083. * Observable raised after camera teleportation
  85084. */
  85085. this.onAfterCameraTeleport = new BABYLON.Observable();
  85086. /**
  85087. * Observable raised when current selected mesh gets unselected
  85088. */
  85089. this.onSelectedMeshUnselected = new BABYLON.Observable();
  85090. /**
  85091. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  85092. */
  85093. this.teleportationEnabled = true;
  85094. this._teleportationInitialized = false;
  85095. this._interactionsEnabled = false;
  85096. this._interactionsRequested = false;
  85097. this._displayGaze = true;
  85098. this._displayLaserPointer = true;
  85099. this._onResize = function () {
  85100. _this.moveButtonToBottomRight();
  85101. if (_this._fullscreenVRpresenting && _this._webVRready) {
  85102. _this.exitVR();
  85103. }
  85104. };
  85105. this._onFullscreenChange = function () {
  85106. if (document.fullscreen !== undefined) {
  85107. _this._fullscreenVRpresenting = document.fullscreen;
  85108. }
  85109. else if (document.mozFullScreen !== undefined) {
  85110. _this._fullscreenVRpresenting = document.mozFullScreen;
  85111. }
  85112. else if (document.webkitIsFullScreen !== undefined) {
  85113. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  85114. }
  85115. else if (document.msIsFullScreen !== undefined) {
  85116. _this._fullscreenVRpresenting = document.msIsFullScreen;
  85117. }
  85118. if (!_this._fullscreenVRpresenting && _this._canvas) {
  85119. _this.exitVR();
  85120. if (!_this._useCustomVRButton) {
  85121. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  85122. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  85123. }
  85124. }
  85125. };
  85126. this.beforeRender = function () {
  85127. if (_this.leftController && _this.leftController._activePointer) {
  85128. _this._castRayAndSelectObject(_this.leftController);
  85129. }
  85130. if (_this.rightController && _this.rightController._activePointer) {
  85131. _this._castRayAndSelectObject(_this.rightController);
  85132. }
  85133. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  85134. _this._castRayAndSelectObject(_this._cameraGazer);
  85135. }
  85136. else {
  85137. _this._cameraGazer._gazeTracker.isVisible = false;
  85138. }
  85139. };
  85140. this._onNewGamepadConnected = function (gamepad) {
  85141. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  85142. if (gamepad.leftStick) {
  85143. gamepad.onleftstickchanged(function (stickValues) {
  85144. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  85145. // Listening to classic/xbox gamepad only if no VR controller is active
  85146. if ((!_this.leftController && !_this.rightController) ||
  85147. ((_this.leftController && !_this.leftController._activePointer) &&
  85148. (_this.rightController && !_this.rightController._activePointer))) {
  85149. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  85150. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  85151. }
  85152. }
  85153. });
  85154. }
  85155. if (gamepad.rightStick) {
  85156. gamepad.onrightstickchanged(function (stickValues) {
  85157. if (_this._teleportationInitialized) {
  85158. _this._checkRotate(stickValues, _this._cameraGazer);
  85159. }
  85160. });
  85161. }
  85162. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  85163. gamepad.onbuttondown(function (buttonPressed) {
  85164. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85165. _this._cameraGazer._selectionPointerDown();
  85166. }
  85167. });
  85168. gamepad.onbuttonup(function (buttonPressed) {
  85169. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85170. _this._cameraGazer._selectionPointerUp();
  85171. }
  85172. });
  85173. }
  85174. }
  85175. else {
  85176. var webVRController = gamepad;
  85177. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  85178. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  85179. _this.rightController = controller;
  85180. }
  85181. else {
  85182. _this.leftController = controller;
  85183. }
  85184. _this._tryEnableInteractionOnController(controller);
  85185. }
  85186. };
  85187. // 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
  85188. this._tryEnableInteractionOnController = function (controller) {
  85189. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  85190. _this._enableInteractionOnController(controller);
  85191. }
  85192. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  85193. _this._enableTeleportationOnController(controller);
  85194. }
  85195. };
  85196. this._onNewGamepadDisconnected = function (gamepad) {
  85197. if (gamepad instanceof BABYLON.WebVRController) {
  85198. if (gamepad.hand === "left" && _this.leftController != null) {
  85199. _this.leftController.dispose();
  85200. _this.leftController = null;
  85201. }
  85202. if (gamepad.hand === "right" && _this.rightController != null) {
  85203. _this.rightController.dispose();
  85204. _this.rightController = null;
  85205. }
  85206. }
  85207. };
  85208. this._workingVector = BABYLON.Vector3.Zero();
  85209. this._workingQuaternion = BABYLON.Quaternion.Identity();
  85210. this._workingMatrix = BABYLON.Matrix.Identity();
  85211. this._scene = scene;
  85212. this._canvas = scene.getEngine().getRenderingCanvas();
  85213. // Parse options
  85214. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  85215. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  85216. }
  85217. if (webVROptions.createDeviceOrientationCamera === undefined) {
  85218. webVROptions.createDeviceOrientationCamera = true;
  85219. }
  85220. if (webVROptions.defaultHeight === undefined) {
  85221. webVROptions.defaultHeight = 1.7;
  85222. }
  85223. if (webVROptions.useCustomVRButton) {
  85224. this._useCustomVRButton = true;
  85225. if (webVROptions.customVRButton) {
  85226. this._btnVR = webVROptions.customVRButton;
  85227. }
  85228. }
  85229. if (webVROptions.rayLength) {
  85230. this._rayLength = webVROptions.rayLength;
  85231. }
  85232. this._defaultHeight = webVROptions.defaultHeight;
  85233. if (webVROptions.positionScale) {
  85234. this._rayLength *= webVROptions.positionScale;
  85235. this._defaultHeight *= webVROptions.positionScale;
  85236. }
  85237. // Set position
  85238. if (this._scene.activeCamera) {
  85239. this._position = this._scene.activeCamera.position.clone();
  85240. }
  85241. else {
  85242. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  85243. }
  85244. // Set non-vr camera
  85245. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  85246. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  85247. // Copy data from existing camera
  85248. if (this._scene.activeCamera) {
  85249. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  85250. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  85251. // Set rotation from previous camera
  85252. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  85253. var targetCamera = this._scene.activeCamera;
  85254. if (targetCamera.rotationQuaternion) {
  85255. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  85256. }
  85257. else {
  85258. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  85259. }
  85260. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  85261. }
  85262. }
  85263. this._scene.activeCamera = this._deviceOrientationCamera;
  85264. if (this._canvas) {
  85265. this._scene.activeCamera.attachControl(this._canvas);
  85266. }
  85267. }
  85268. else {
  85269. this._existingCamera = this._scene.activeCamera;
  85270. }
  85271. // Create VR cameras
  85272. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85273. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  85274. }
  85275. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  85276. this._webVRCamera.useStandingMatrix();
  85277. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  85278. // Create default button
  85279. if (!this._useCustomVRButton) {
  85280. this._btnVR = document.createElement("BUTTON");
  85281. this._btnVR.className = "babylonVRicon";
  85282. this._btnVR.id = "babylonVRiconbtn";
  85283. this._btnVR.title = "Click to switch to VR";
  85284. 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) }";
  85285. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  85286. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  85287. // css += ".babylonVRicon.vrdisplaysupported { }";
  85288. // css += ".babylonVRicon.vrdisplayready { }";
  85289. // css += ".babylonVRicon.vrdisplayrequesting { }";
  85290. var style = document.createElement('style');
  85291. style.appendChild(document.createTextNode(css));
  85292. document.getElementsByTagName('head')[0].appendChild(style);
  85293. this.moveButtonToBottomRight();
  85294. }
  85295. // VR button click event
  85296. if (this._btnVR) {
  85297. this._btnVR.addEventListener("click", function () {
  85298. if (!_this.isInVRMode) {
  85299. _this.enterVR();
  85300. }
  85301. else {
  85302. _this.exitVR();
  85303. }
  85304. });
  85305. }
  85306. // Window events
  85307. window.addEventListener("resize", this._onResize);
  85308. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  85309. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  85310. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  85311. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  85312. // Display vr button when headset is connected
  85313. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85314. this.displayVRButton();
  85315. }
  85316. else {
  85317. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  85318. if (e.vrDisplay) {
  85319. _this.displayVRButton();
  85320. }
  85321. });
  85322. }
  85323. // Exiting VR mode using 'ESC' key on desktop
  85324. this._onKeyDown = function (event) {
  85325. if (event.keyCode === 27 && _this.isInVRMode) {
  85326. _this.exitVR();
  85327. }
  85328. };
  85329. document.addEventListener("keydown", this._onKeyDown);
  85330. // Exiting VR mode double tapping the touch screen
  85331. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  85332. if (_this.isInVRMode) {
  85333. _this.exitVR();
  85334. if (_this._fullscreenVRpresenting) {
  85335. _this._scene.getEngine().switchFullscreen(true);
  85336. }
  85337. }
  85338. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  85339. // Listen for WebVR display changes
  85340. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  85341. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  85342. this._onVRRequestPresentStart = function () {
  85343. _this._webVRrequesting = true;
  85344. _this.updateButtonVisibility();
  85345. };
  85346. this._onVRRequestPresentComplete = function (success) {
  85347. _this._webVRrequesting = false;
  85348. _this.updateButtonVisibility();
  85349. };
  85350. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  85351. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  85352. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  85353. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  85354. scene.onDisposeObservable.add(function () {
  85355. _this.dispose();
  85356. });
  85357. // Gamepad connection events
  85358. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  85359. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  85360. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  85361. this.updateButtonVisibility();
  85362. //create easing functions
  85363. this._circleEase = new BABYLON.CircleEase();
  85364. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85365. }
  85366. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  85367. /** Return this.onEnteringVRObservable
  85368. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  85369. */
  85370. get: function () {
  85371. return this.onEnteringVRObservable;
  85372. },
  85373. enumerable: true,
  85374. configurable: true
  85375. });
  85376. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  85377. /** Return this.onExitingVRObservable
  85378. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  85379. */
  85380. get: function () {
  85381. return this.onExitingVRObservable;
  85382. },
  85383. enumerable: true,
  85384. configurable: true
  85385. });
  85386. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  85387. /** Return this.onControllerMeshLoadedObservable
  85388. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  85389. */
  85390. get: function () {
  85391. return this.onControllerMeshLoadedObservable;
  85392. },
  85393. enumerable: true,
  85394. configurable: true
  85395. });
  85396. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  85397. /**
  85398. * The mesh used to display where the user is going to teleport.
  85399. */
  85400. get: function () {
  85401. return this._teleportationTarget;
  85402. },
  85403. /**
  85404. * Sets the mesh to be used to display where the user is going to teleport.
  85405. */
  85406. set: function (value) {
  85407. if (value) {
  85408. value.name = "teleportationTarget";
  85409. this._isDefaultTeleportationTarget = false;
  85410. this._teleportationTarget = value;
  85411. }
  85412. },
  85413. enumerable: true,
  85414. configurable: true
  85415. });
  85416. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  85417. /**
  85418. * The mesh used to display where the user is selecting,
  85419. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  85420. * See http://doc.babylonjs.com/resources/baking_transformations
  85421. */
  85422. get: function () {
  85423. return this._cameraGazer._gazeTracker;
  85424. },
  85425. set: function (value) {
  85426. if (value) {
  85427. this._cameraGazer._gazeTracker = value;
  85428. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  85429. this._cameraGazer._gazeTracker.isPickable = false;
  85430. this._cameraGazer._gazeTracker.isVisible = false;
  85431. this._cameraGazer._gazeTracker.name = "gazeTracker";
  85432. if (this.leftController) {
  85433. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85434. }
  85435. if (this.rightController) {
  85436. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85437. }
  85438. }
  85439. },
  85440. enumerable: true,
  85441. configurable: true
  85442. });
  85443. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  85444. /**
  85445. * If the ray of the gaze should be displayed.
  85446. */
  85447. get: function () {
  85448. return this._displayGaze;
  85449. },
  85450. /**
  85451. * Sets if the ray of the gaze should be displayed.
  85452. */
  85453. set: function (value) {
  85454. this._displayGaze = value;
  85455. if (!value) {
  85456. this._cameraGazer._gazeTracker.isVisible = false;
  85457. if (this.leftController) {
  85458. this.leftController._gazeTracker.isVisible = false;
  85459. }
  85460. if (this.rightController) {
  85461. this.rightController._gazeTracker.isVisible = false;
  85462. }
  85463. }
  85464. },
  85465. enumerable: true,
  85466. configurable: true
  85467. });
  85468. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  85469. /**
  85470. * If the ray of the LaserPointer should be displayed.
  85471. */
  85472. get: function () {
  85473. return this._displayLaserPointer;
  85474. },
  85475. /**
  85476. * Sets if the ray of the LaserPointer should be displayed.
  85477. */
  85478. set: function (value) {
  85479. this._displayLaserPointer = value;
  85480. if (!value) {
  85481. if (this.rightController) {
  85482. this.rightController._deactivatePointer();
  85483. this.rightController._gazeTracker.isVisible = false;
  85484. }
  85485. if (this.leftController) {
  85486. this.leftController._deactivatePointer();
  85487. this.leftController._gazeTracker.isVisible = false;
  85488. }
  85489. }
  85490. else {
  85491. if (this.rightController) {
  85492. this.rightController._activatePointer();
  85493. }
  85494. else if (this.leftController) {
  85495. this.leftController._activatePointer();
  85496. }
  85497. }
  85498. },
  85499. enumerable: true,
  85500. configurable: true
  85501. });
  85502. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  85503. /**
  85504. * The deviceOrientationCamera used as the camera when not in VR.
  85505. */
  85506. get: function () {
  85507. return this._deviceOrientationCamera;
  85508. },
  85509. enumerable: true,
  85510. configurable: true
  85511. });
  85512. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  85513. /**
  85514. * Based on the current WebVR support, returns the current VR camera used.
  85515. */
  85516. get: function () {
  85517. if (this._webVRready) {
  85518. return this._webVRCamera;
  85519. }
  85520. else {
  85521. return this._scene.activeCamera;
  85522. }
  85523. },
  85524. enumerable: true,
  85525. configurable: true
  85526. });
  85527. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  85528. /**
  85529. * The webVRCamera which is used when in VR.
  85530. */
  85531. get: function () {
  85532. return this._webVRCamera;
  85533. },
  85534. enumerable: true,
  85535. configurable: true
  85536. });
  85537. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  85538. /**
  85539. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  85540. */
  85541. get: function () {
  85542. return this._vrDeviceOrientationCamera;
  85543. },
  85544. enumerable: true,
  85545. configurable: true
  85546. });
  85547. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  85548. get: function () {
  85549. var result = this._cameraGazer._teleportationRequestInitiated
  85550. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  85551. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  85552. return result;
  85553. },
  85554. enumerable: true,
  85555. configurable: true
  85556. });
  85557. // Raised when one of the controller has loaded successfully its associated default mesh
  85558. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  85559. if (this.leftController && this.leftController.webVRController == webVRController) {
  85560. if (webVRController.mesh) {
  85561. this.leftController._setLaserPointerParent(webVRController.mesh);
  85562. }
  85563. }
  85564. if (this.rightController && this.rightController.webVRController == webVRController) {
  85565. if (webVRController.mesh) {
  85566. this.rightController._setLaserPointerParent(webVRController.mesh);
  85567. }
  85568. }
  85569. try {
  85570. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  85571. }
  85572. catch (err) {
  85573. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  85574. }
  85575. };
  85576. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  85577. /**
  85578. * Gets a value indicating if we are currently in VR mode.
  85579. */
  85580. get: function () {
  85581. return this._webVRpresenting || this._fullscreenVRpresenting;
  85582. },
  85583. enumerable: true,
  85584. configurable: true
  85585. });
  85586. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  85587. var vrDisplay = this._scene.getEngine().getVRDevice();
  85588. if (vrDisplay) {
  85589. var wasPresenting = this._webVRpresenting;
  85590. // A VR display is connected
  85591. this._webVRpresenting = vrDisplay.isPresenting;
  85592. if (wasPresenting && !this._webVRpresenting)
  85593. this.exitVR();
  85594. }
  85595. else {
  85596. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  85597. }
  85598. this.updateButtonVisibility();
  85599. };
  85600. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  85601. this._webVRsupported = eventArgs.vrSupported;
  85602. this._webVRready = !!eventArgs.vrDisplay;
  85603. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  85604. this.updateButtonVisibility();
  85605. };
  85606. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  85607. if (this._canvas && !this._useCustomVRButton) {
  85608. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  85609. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  85610. }
  85611. };
  85612. VRExperienceHelper.prototype.displayVRButton = function () {
  85613. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  85614. document.body.appendChild(this._btnVR);
  85615. this._btnVRDisplayed = true;
  85616. }
  85617. };
  85618. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  85619. if (!this._btnVR || this._useCustomVRButton) {
  85620. return;
  85621. }
  85622. this._btnVR.className = "babylonVRicon";
  85623. if (this.isInVRMode) {
  85624. this._btnVR.className += " vrdisplaypresenting";
  85625. }
  85626. else {
  85627. if (this._webVRready)
  85628. this._btnVR.className += " vrdisplayready";
  85629. if (this._webVRsupported)
  85630. this._btnVR.className += " vrdisplaysupported";
  85631. if (this._webVRrequesting)
  85632. this._btnVR.className += " vrdisplayrequesting";
  85633. }
  85634. };
  85635. /**
  85636. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  85637. * Otherwise, will use the fullscreen API.
  85638. */
  85639. VRExperienceHelper.prototype.enterVR = function () {
  85640. if (this.onEnteringVRObservable) {
  85641. try {
  85642. this.onEnteringVRObservable.notifyObservers(this);
  85643. }
  85644. catch (err) {
  85645. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  85646. }
  85647. }
  85648. if (this._scene.activeCamera) {
  85649. this._position = this._scene.activeCamera.position.clone();
  85650. // make sure that we return to the last active camera
  85651. this._existingCamera = this._scene.activeCamera;
  85652. }
  85653. if (this._webVRrequesting)
  85654. return;
  85655. // If WebVR is supported and a headset is connected
  85656. if (this._webVRready) {
  85657. if (!this._webVRpresenting) {
  85658. this._webVRCamera.position = this._position;
  85659. this._scene.activeCamera = this._webVRCamera;
  85660. }
  85661. }
  85662. else if (this._vrDeviceOrientationCamera) {
  85663. this._vrDeviceOrientationCamera.position = this._position;
  85664. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  85665. this._scene.getEngine().switchFullscreen(true);
  85666. this.updateButtonVisibility();
  85667. }
  85668. if (this._scene.activeCamera && this._canvas) {
  85669. this._scene.activeCamera.attachControl(this._canvas);
  85670. }
  85671. if (this._interactionsEnabled) {
  85672. this._scene.registerBeforeRender(this.beforeRender);
  85673. }
  85674. };
  85675. /**
  85676. * Attempt to exit VR, or fullscreen.
  85677. */
  85678. VRExperienceHelper.prototype.exitVR = function () {
  85679. if (this.onExitingVRObservable) {
  85680. try {
  85681. this.onExitingVRObservable.notifyObservers(this);
  85682. }
  85683. catch (err) {
  85684. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  85685. }
  85686. }
  85687. if (this._webVRpresenting) {
  85688. this._scene.getEngine().disableVR();
  85689. }
  85690. if (this._scene.activeCamera) {
  85691. this._position = this._scene.activeCamera.position.clone();
  85692. }
  85693. if (this._deviceOrientationCamera) {
  85694. this._deviceOrientationCamera.position = this._position;
  85695. this._scene.activeCamera = this._deviceOrientationCamera;
  85696. if (this._canvas) {
  85697. this._scene.activeCamera.attachControl(this._canvas);
  85698. }
  85699. }
  85700. else if (this._existingCamera) {
  85701. this._existingCamera.position = this._position;
  85702. this._scene.activeCamera = this._existingCamera;
  85703. }
  85704. this.updateButtonVisibility();
  85705. if (this._interactionsEnabled) {
  85706. this._scene.unregisterBeforeRender(this.beforeRender);
  85707. }
  85708. };
  85709. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  85710. /**
  85711. * The position of the vr experience helper.
  85712. */
  85713. get: function () {
  85714. return this._position;
  85715. },
  85716. /**
  85717. * Sets the position of the vr experience helper.
  85718. */
  85719. set: function (value) {
  85720. this._position = value;
  85721. if (this._scene.activeCamera) {
  85722. this._scene.activeCamera.position = value;
  85723. }
  85724. },
  85725. enumerable: true,
  85726. configurable: true
  85727. });
  85728. /**
  85729. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  85730. */
  85731. VRExperienceHelper.prototype.enableInteractions = function () {
  85732. var _this = this;
  85733. if (!this._interactionsEnabled) {
  85734. this._interactionsRequested = true;
  85735. if (this.leftController) {
  85736. this._enableInteractionOnController(this.leftController);
  85737. }
  85738. if (this.rightController) {
  85739. this._enableInteractionOnController(this.rightController);
  85740. }
  85741. this.raySelectionPredicate = function (mesh) {
  85742. return mesh.isVisible;
  85743. };
  85744. this.meshSelectionPredicate = function (mesh) {
  85745. return true;
  85746. };
  85747. this._raySelectionPredicate = function (mesh) {
  85748. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  85749. && mesh.name.indexOf("teleportationTarget") === -1
  85750. && mesh.name.indexOf("torusTeleportation") === -1
  85751. && mesh.name.indexOf("laserPointer") === -1)) {
  85752. return _this.raySelectionPredicate(mesh);
  85753. }
  85754. return false;
  85755. };
  85756. this._interactionsEnabled = true;
  85757. }
  85758. };
  85759. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  85760. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  85761. if (this._floorMeshesCollection[i].id === mesh.id) {
  85762. return true;
  85763. }
  85764. }
  85765. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  85766. return true;
  85767. }
  85768. return false;
  85769. };
  85770. /**
  85771. * Adds a floor mesh to be used for teleportation.
  85772. * @param floorMesh the mesh to be used for teleportation.
  85773. */
  85774. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  85775. if (!this._floorMeshesCollection) {
  85776. return;
  85777. }
  85778. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  85779. return;
  85780. }
  85781. this._floorMeshesCollection.push(floorMesh);
  85782. };
  85783. /**
  85784. * Removes a floor mesh from being used for teleportation.
  85785. * @param floorMesh the mesh to be removed.
  85786. */
  85787. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  85788. if (!this._floorMeshesCollection) {
  85789. return;
  85790. }
  85791. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  85792. if (meshIndex !== -1) {
  85793. this._floorMeshesCollection.splice(meshIndex, 1);
  85794. }
  85795. };
  85796. /**
  85797. * Enables interactions and teleportation using the VR controllers and gaze.
  85798. * @param vrTeleportationOptions options to modify teleportation behavior.
  85799. */
  85800. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  85801. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  85802. if (!this._teleportationInitialized) {
  85803. this._teleportationRequested = true;
  85804. this.enableInteractions();
  85805. if (vrTeleportationOptions.floorMeshName) {
  85806. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  85807. }
  85808. if (vrTeleportationOptions.floorMeshes) {
  85809. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  85810. }
  85811. if (this.leftController != null) {
  85812. this._enableTeleportationOnController(this.leftController);
  85813. }
  85814. if (this.rightController != null) {
  85815. this._enableTeleportationOnController(this.rightController);
  85816. }
  85817. // Creates an image processing post process for the vignette not relying
  85818. // on the main scene configuration for image processing to reduce setup and spaces
  85819. // (gamma/linear) conflicts.
  85820. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  85821. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  85822. imageProcessingConfiguration.vignetteEnabled = true;
  85823. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  85824. this._webVRCamera.detachPostProcess(this._postProcessMove);
  85825. this._teleportationInitialized = true;
  85826. if (this._isDefaultTeleportationTarget) {
  85827. this._createTeleportationCircles();
  85828. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  85829. }
  85830. }
  85831. };
  85832. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  85833. var _this = this;
  85834. var controllerMesh = controller.webVRController.mesh;
  85835. if (controllerMesh) {
  85836. controller._interactionsEnabled = true;
  85837. controller._activatePointer();
  85838. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  85839. // Enabling / disabling laserPointer
  85840. if (_this._displayLaserPointer && stateObject.value === 1) {
  85841. if (controller._activePointer) {
  85842. controller._deactivatePointer();
  85843. }
  85844. else {
  85845. controller._activatePointer();
  85846. }
  85847. if (_this.displayGaze) {
  85848. controller._gazeTracker.isVisible = controller._activePointer;
  85849. }
  85850. }
  85851. });
  85852. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  85853. if (!controller._pointerDownOnMeshAsked) {
  85854. if (stateObject.value > _this._padSensibilityUp) {
  85855. controller._selectionPointerDown();
  85856. }
  85857. }
  85858. else if (stateObject.value < _this._padSensibilityDown) {
  85859. controller._selectionPointerUp();
  85860. }
  85861. });
  85862. }
  85863. };
  85864. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  85865. // Dont teleport if another gaze already requested teleportation
  85866. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  85867. return;
  85868. }
  85869. if (!gazer._teleportationRequestInitiated) {
  85870. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  85871. gazer._activatePointer();
  85872. gazer._teleportationRequestInitiated = true;
  85873. }
  85874. }
  85875. else {
  85876. // Listening to the proper controller values changes to confirm teleportation
  85877. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  85878. if (this._teleportActive) {
  85879. this._teleportCamera(this._haloCenter);
  85880. }
  85881. gazer._teleportationRequestInitiated = false;
  85882. }
  85883. }
  85884. };
  85885. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  85886. // Only rotate when user is not currently selecting a teleportation location
  85887. if (gazer._teleportationRequestInitiated) {
  85888. return;
  85889. }
  85890. if (!this._rotationLeftAsked) {
  85891. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  85892. this._rotationLeftAsked = true;
  85893. if (this._rotationAllowed) {
  85894. this._rotateCamera(false);
  85895. }
  85896. }
  85897. }
  85898. else {
  85899. if (stateObject.x > -this._padSensibilityDown) {
  85900. this._rotationLeftAsked = false;
  85901. }
  85902. }
  85903. if (!this._rotationRightAsked) {
  85904. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  85905. this._rotationRightAsked = true;
  85906. if (this._rotationAllowed) {
  85907. this._rotateCamera(true);
  85908. }
  85909. }
  85910. }
  85911. else {
  85912. if (stateObject.x < this._padSensibilityDown) {
  85913. this._rotationRightAsked = false;
  85914. }
  85915. }
  85916. };
  85917. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  85918. // Only teleport backwards when user is not currently selecting a teleportation location
  85919. if (gazer._teleportationRequestInitiated) {
  85920. return;
  85921. }
  85922. // Teleport backwards
  85923. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  85924. if (!gazer._teleportationBackRequestInitiated) {
  85925. if (!this.currentVRCamera) {
  85926. return;
  85927. }
  85928. // Get rotation and position of the current camera
  85929. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  85930. var position = this.currentVRCamera.position;
  85931. // If the camera has device position, use that instead
  85932. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  85933. rotation = this.currentVRCamera.deviceRotationQuaternion;
  85934. position = this.currentVRCamera.devicePosition;
  85935. }
  85936. // Get matrix with only the y rotation of the device rotation
  85937. rotation.toEulerAnglesToRef(this._workingVector);
  85938. this._workingVector.z = 0;
  85939. this._workingVector.x = 0;
  85940. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  85941. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  85942. // Rotate backwards ray by device rotation to cast at the ground behind the user
  85943. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  85944. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  85945. var ray = new BABYLON.Ray(position, this._workingVector);
  85946. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  85947. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  85948. this._teleportCamera(hit.pickedPoint);
  85949. }
  85950. gazer._teleportationBackRequestInitiated = true;
  85951. }
  85952. }
  85953. else {
  85954. gazer._teleportationBackRequestInitiated = false;
  85955. }
  85956. };
  85957. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  85958. var _this = this;
  85959. var controllerMesh = controller.webVRController.mesh;
  85960. if (controllerMesh) {
  85961. if (!controller._interactionsEnabled) {
  85962. this._enableInteractionOnController(controller);
  85963. }
  85964. controller._interactionsEnabled = true;
  85965. controller._teleportationEnabled = true;
  85966. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85967. controller._dpadPressed = false;
  85968. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  85969. controller._dpadPressed = stateObject.pressed;
  85970. if (!controller._dpadPressed) {
  85971. _this._rotationLeftAsked = false;
  85972. _this._rotationRightAsked = false;
  85973. controller._teleportationBackRequestInitiated = false;
  85974. }
  85975. });
  85976. }
  85977. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  85978. if (_this.teleportationEnabled) {
  85979. _this._checkTeleportBackwards(stateObject, controller);
  85980. _this._checkTeleportWithRay(stateObject, controller);
  85981. }
  85982. _this._checkRotate(stateObject, controller);
  85983. });
  85984. }
  85985. };
  85986. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  85987. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  85988. this._teleportationTarget.isPickable = false;
  85989. var length = 512;
  85990. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  85991. dynamicTexture.hasAlpha = true;
  85992. var context = dynamicTexture.getContext();
  85993. var centerX = length / 2;
  85994. var centerY = length / 2;
  85995. var radius = 200;
  85996. context.beginPath();
  85997. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  85998. context.fillStyle = this._teleportationFillColor;
  85999. context.fill();
  86000. context.lineWidth = 10;
  86001. context.strokeStyle = this._teleportationBorderColor;
  86002. context.stroke();
  86003. context.closePath();
  86004. dynamicTexture.update();
  86005. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  86006. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  86007. this._teleportationTarget.material = teleportationCircleMaterial;
  86008. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  86009. torus.isPickable = false;
  86010. torus.parent = this._teleportationTarget;
  86011. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86012. var keys = [];
  86013. keys.push({
  86014. frame: 0,
  86015. value: 0
  86016. });
  86017. keys.push({
  86018. frame: 30,
  86019. value: 0.4
  86020. });
  86021. keys.push({
  86022. frame: 60,
  86023. value: 0
  86024. });
  86025. animationInnerCircle.setKeys(keys);
  86026. var easingFunction = new BABYLON.SineEase();
  86027. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86028. animationInnerCircle.setEasingFunction(easingFunction);
  86029. torus.animations = [];
  86030. torus.animations.push(animationInnerCircle);
  86031. this._scene.beginAnimation(torus, 0, 60, true);
  86032. this._hideTeleportationTarget();
  86033. };
  86034. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  86035. this._teleportActive = true;
  86036. if (this._teleportationInitialized) {
  86037. this._teleportationTarget.isVisible = true;
  86038. if (this._isDefaultTeleportationTarget) {
  86039. this._teleportationTarget.getChildren()[0].isVisible = true;
  86040. }
  86041. }
  86042. };
  86043. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  86044. this._teleportActive = false;
  86045. if (this._teleportationInitialized) {
  86046. this._teleportationTarget.isVisible = false;
  86047. if (this._isDefaultTeleportationTarget) {
  86048. this._teleportationTarget.getChildren()[0].isVisible = false;
  86049. }
  86050. }
  86051. };
  86052. VRExperienceHelper.prototype._rotateCamera = function (right) {
  86053. var _this = this;
  86054. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86055. return;
  86056. }
  86057. if (right) {
  86058. this._rotationAngle++;
  86059. }
  86060. else {
  86061. this._rotationAngle--;
  86062. }
  86063. this.currentVRCamera.animations = [];
  86064. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  86065. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86066. var animationRotationKeys = [];
  86067. animationRotationKeys.push({
  86068. frame: 0,
  86069. value: this.currentVRCamera.rotationQuaternion
  86070. });
  86071. animationRotationKeys.push({
  86072. frame: 6,
  86073. value: target
  86074. });
  86075. animationRotation.setKeys(animationRotationKeys);
  86076. animationRotation.setEasingFunction(this._circleEase);
  86077. this.currentVRCamera.animations.push(animationRotation);
  86078. this._postProcessMove.animations = [];
  86079. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86080. var vignetteWeightKeys = [];
  86081. vignetteWeightKeys.push({
  86082. frame: 0,
  86083. value: 0
  86084. });
  86085. vignetteWeightKeys.push({
  86086. frame: 3,
  86087. value: 4
  86088. });
  86089. vignetteWeightKeys.push({
  86090. frame: 6,
  86091. value: 0
  86092. });
  86093. animationPP.setKeys(vignetteWeightKeys);
  86094. animationPP.setEasingFunction(this._circleEase);
  86095. this._postProcessMove.animations.push(animationPP);
  86096. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86097. var vignetteStretchKeys = [];
  86098. vignetteStretchKeys.push({
  86099. frame: 0,
  86100. value: 0
  86101. });
  86102. vignetteStretchKeys.push({
  86103. frame: 3,
  86104. value: 10
  86105. });
  86106. vignetteStretchKeys.push({
  86107. frame: 6,
  86108. value: 0
  86109. });
  86110. animationPP2.setKeys(vignetteStretchKeys);
  86111. animationPP2.setEasingFunction(this._circleEase);
  86112. this._postProcessMove.animations.push(animationPP2);
  86113. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86114. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86115. this._postProcessMove.samples = 4;
  86116. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86117. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  86118. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86119. });
  86120. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  86121. };
  86122. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  86123. if (hit.pickedPoint) {
  86124. if (gazer._teleportationRequestInitiated) {
  86125. this._displayTeleportationTarget();
  86126. this._haloCenter.copyFrom(hit.pickedPoint);
  86127. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  86128. }
  86129. var pickNormal = hit.getNormal(true, false);
  86130. if (pickNormal) {
  86131. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86132. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86133. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  86134. }
  86135. this._teleportationTarget.position.y += 0.1;
  86136. }
  86137. };
  86138. VRExperienceHelper.prototype._teleportCamera = function (location) {
  86139. var _this = this;
  86140. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86141. return;
  86142. }
  86143. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  86144. // offset of the headset from the anchor.
  86145. if (this.webVRCamera.leftCamera) {
  86146. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  86147. this._workingVector.subtractInPlace(this.webVRCamera.position);
  86148. location.subtractToRef(this._workingVector, this._workingVector);
  86149. }
  86150. else {
  86151. this._workingVector.copyFrom(location);
  86152. }
  86153. // Add height to account for user's height offset
  86154. if (this.isInVRMode) {
  86155. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  86156. }
  86157. else {
  86158. this._workingVector.y += this._defaultHeight;
  86159. }
  86160. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  86161. // Create animation from the camera's position to the new location
  86162. this.currentVRCamera.animations = [];
  86163. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86164. var animationCameraTeleportationKeys = [{
  86165. frame: 0,
  86166. value: this.currentVRCamera.position
  86167. },
  86168. {
  86169. frame: 11,
  86170. value: this._workingVector
  86171. }
  86172. ];
  86173. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  86174. animationCameraTeleportation.setEasingFunction(this._circleEase);
  86175. this.currentVRCamera.animations.push(animationCameraTeleportation);
  86176. this._postProcessMove.animations = [];
  86177. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86178. var vignetteWeightKeys = [];
  86179. vignetteWeightKeys.push({
  86180. frame: 0,
  86181. value: 0
  86182. });
  86183. vignetteWeightKeys.push({
  86184. frame: 5,
  86185. value: 8
  86186. });
  86187. vignetteWeightKeys.push({
  86188. frame: 11,
  86189. value: 0
  86190. });
  86191. animationPP.setKeys(vignetteWeightKeys);
  86192. this._postProcessMove.animations.push(animationPP);
  86193. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86194. var vignetteStretchKeys = [];
  86195. vignetteStretchKeys.push({
  86196. frame: 0,
  86197. value: 0
  86198. });
  86199. vignetteStretchKeys.push({
  86200. frame: 5,
  86201. value: 10
  86202. });
  86203. vignetteStretchKeys.push({
  86204. frame: 11,
  86205. value: 0
  86206. });
  86207. animationPP2.setKeys(vignetteStretchKeys);
  86208. this._postProcessMove.animations.push(animationPP2);
  86209. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86210. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86211. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86212. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  86213. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86214. });
  86215. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  86216. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  86217. });
  86218. this._hideTeleportationTarget();
  86219. };
  86220. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  86221. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86222. return;
  86223. }
  86224. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  86225. // Moving the gazeTracker on the mesh face targetted
  86226. if (hit && hit.pickedPoint) {
  86227. if (this._displayGaze) {
  86228. var multiplier = 1;
  86229. gazer._gazeTracker.isVisible = true;
  86230. if (gazer._isActionableMesh) {
  86231. multiplier = 3;
  86232. }
  86233. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  86234. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  86235. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  86236. var pickNormal = hit.getNormal();
  86237. // To avoid z-fighting
  86238. var deltaFighting = 0.002;
  86239. if (pickNormal) {
  86240. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86241. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86242. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  86243. }
  86244. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  86245. if (gazer._gazeTracker.position.x < 0) {
  86246. gazer._gazeTracker.position.x += deltaFighting;
  86247. }
  86248. else {
  86249. gazer._gazeTracker.position.x -= deltaFighting;
  86250. }
  86251. if (gazer._gazeTracker.position.y < 0) {
  86252. gazer._gazeTracker.position.y += deltaFighting;
  86253. }
  86254. else {
  86255. gazer._gazeTracker.position.y -= deltaFighting;
  86256. }
  86257. if (gazer._gazeTracker.position.z < 0) {
  86258. gazer._gazeTracker.position.z += deltaFighting;
  86259. }
  86260. else {
  86261. gazer._gazeTracker.position.z -= deltaFighting;
  86262. }
  86263. }
  86264. // Changing the size of the laser pointer based on the distance from the targetted point
  86265. gazer._updatePointerDistance(hit.distance);
  86266. }
  86267. else {
  86268. gazer._gazeTracker.isVisible = false;
  86269. }
  86270. if (hit && hit.pickedMesh) {
  86271. gazer._currentHit = hit;
  86272. if (gazer._pointerDownOnMeshAsked) {
  86273. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  86274. }
  86275. // The object selected is the floor, we're in a teleportation scenario
  86276. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  86277. // Moving the teleportation area to this targetted point
  86278. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  86279. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  86280. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86281. }
  86282. gazer._currentMeshSelected = null;
  86283. if (gazer._teleportationRequestInitiated) {
  86284. this._moveTeleportationSelectorTo(hit, gazer);
  86285. }
  86286. return;
  86287. }
  86288. // If not, we're in a selection scenario
  86289. //this._teleportationAllowed = false;
  86290. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  86291. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  86292. this.onNewMeshPicked.notifyObservers(hit);
  86293. gazer._currentMeshSelected = hit.pickedMesh;
  86294. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  86295. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  86296. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  86297. gazer._isActionableMesh = true;
  86298. }
  86299. else {
  86300. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86301. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86302. gazer._isActionableMesh = false;
  86303. }
  86304. try {
  86305. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  86306. }
  86307. catch (err) {
  86308. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  86309. }
  86310. }
  86311. else {
  86312. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86313. gazer._currentMeshSelected = null;
  86314. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86315. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86316. }
  86317. }
  86318. }
  86319. else {
  86320. gazer._currentHit = null;
  86321. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86322. gazer._currentMeshSelected = null;
  86323. //this._teleportationAllowed = false;
  86324. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86325. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86326. }
  86327. };
  86328. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  86329. if (mesh) {
  86330. this.onSelectedMeshUnselected.notifyObservers(mesh);
  86331. }
  86332. };
  86333. /**
  86334. * Sets the color of the laser ray from the vr controllers.
  86335. * @param color new color for the ray.
  86336. */
  86337. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  86338. if (this.leftController) {
  86339. this.leftController._setLaserPointerColor(color);
  86340. }
  86341. if (this.rightController) {
  86342. this.rightController._setLaserPointerColor(color);
  86343. }
  86344. };
  86345. /**
  86346. * Sets the color of the ray from the vr headsets gaze.
  86347. * @param color new color for the ray.
  86348. */
  86349. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  86350. if (!this._cameraGazer._gazeTracker.material) {
  86351. return;
  86352. }
  86353. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  86354. if (this.leftController) {
  86355. this.leftController._gazeTracker.material.emissiveColor = color;
  86356. }
  86357. if (this.rightController) {
  86358. this.rightController._gazeTracker.material.emissiveColor = color;
  86359. }
  86360. };
  86361. /**
  86362. * Exits VR and disposes of the vr experience helper
  86363. */
  86364. VRExperienceHelper.prototype.dispose = function () {
  86365. if (this.isInVRMode) {
  86366. this.exitVR();
  86367. }
  86368. if (this._postProcessMove) {
  86369. this._postProcessMove.dispose();
  86370. }
  86371. if (this._webVRCamera) {
  86372. this._webVRCamera.dispose();
  86373. }
  86374. if (this._vrDeviceOrientationCamera) {
  86375. this._vrDeviceOrientationCamera.dispose();
  86376. }
  86377. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  86378. document.body.removeChild(this._btnVR);
  86379. }
  86380. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  86381. this._deviceOrientationCamera.dispose();
  86382. }
  86383. if (this._cameraGazer) {
  86384. this._cameraGazer.dispose();
  86385. }
  86386. if (this.leftController) {
  86387. this.leftController.dispose();
  86388. }
  86389. if (this.rightController) {
  86390. this.rightController.dispose();
  86391. }
  86392. if (this._teleportationTarget) {
  86393. this._teleportationTarget.dispose();
  86394. }
  86395. this._floorMeshesCollection = [];
  86396. document.removeEventListener("keydown", this._onKeyDown);
  86397. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86398. window.removeEventListener("resize", this._onResize);
  86399. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  86400. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  86401. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  86402. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  86403. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  86404. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  86405. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  86406. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86407. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  86408. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  86409. this._scene.unregisterBeforeRender(this.beforeRender);
  86410. };
  86411. /**
  86412. * Gets the name of the VRExperienceHelper class
  86413. * @returns "VRExperienceHelper"
  86414. */
  86415. VRExperienceHelper.prototype.getClassName = function () {
  86416. return "VRExperienceHelper";
  86417. };
  86418. return VRExperienceHelper;
  86419. }());
  86420. BABYLON.VRExperienceHelper = VRExperienceHelper;
  86421. })(BABYLON || (BABYLON = {}));
  86422. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  86423. "use strict";
  86424. // Mainly based on these 2 articles :
  86425. // 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
  86426. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  86427. var BABYLON;
  86428. (function (BABYLON) {
  86429. var JoystickAxis;
  86430. (function (JoystickAxis) {
  86431. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  86432. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  86433. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  86434. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  86435. var VirtualJoystick = /** @class */ (function () {
  86436. function VirtualJoystick(leftJoystick) {
  86437. var _this = this;
  86438. if (leftJoystick) {
  86439. this._leftJoystick = true;
  86440. }
  86441. else {
  86442. this._leftJoystick = false;
  86443. }
  86444. VirtualJoystick._globalJoystickIndex++;
  86445. // By default left & right arrow keys are moving the X
  86446. // and up & down keys are moving the Y
  86447. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86448. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86449. this.reverseLeftRight = false;
  86450. this.reverseUpDown = false;
  86451. // collections of pointers
  86452. this._touches = new BABYLON.StringDictionary();
  86453. this.deltaPosition = BABYLON.Vector3.Zero();
  86454. this._joystickSensibility = 25;
  86455. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86456. this._onResize = function (evt) {
  86457. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86458. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86459. if (VirtualJoystick.vjCanvas) {
  86460. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  86461. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  86462. }
  86463. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  86464. };
  86465. // injecting a canvas element on top of the canvas 3D game
  86466. if (!VirtualJoystick.vjCanvas) {
  86467. window.addEventListener("resize", this._onResize, false);
  86468. VirtualJoystick.vjCanvas = document.createElement("canvas");
  86469. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86470. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86471. VirtualJoystick.vjCanvas.width = window.innerWidth;
  86472. VirtualJoystick.vjCanvas.height = window.innerHeight;
  86473. VirtualJoystick.vjCanvas.style.width = "100%";
  86474. VirtualJoystick.vjCanvas.style.height = "100%";
  86475. VirtualJoystick.vjCanvas.style.position = "absolute";
  86476. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  86477. VirtualJoystick.vjCanvas.style.top = "0px";
  86478. VirtualJoystick.vjCanvas.style.left = "0px";
  86479. VirtualJoystick.vjCanvas.style.zIndex = "5";
  86480. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  86481. // Support for jQuery PEP polyfill
  86482. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  86483. var context = VirtualJoystick.vjCanvas.getContext('2d');
  86484. if (!context) {
  86485. throw new Error("Unable to create canvas for virtual joystick");
  86486. }
  86487. VirtualJoystick.vjCanvasContext = context;
  86488. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  86489. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86490. document.body.appendChild(VirtualJoystick.vjCanvas);
  86491. }
  86492. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  86493. this.pressed = false;
  86494. // default joystick color
  86495. this._joystickColor = "cyan";
  86496. this._joystickPointerID = -1;
  86497. // current joystick position
  86498. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  86499. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  86500. // origin joystick position
  86501. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  86502. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  86503. this._onPointerDownHandlerRef = function (evt) {
  86504. _this._onPointerDown(evt);
  86505. };
  86506. this._onPointerMoveHandlerRef = function (evt) {
  86507. _this._onPointerMove(evt);
  86508. };
  86509. this._onPointerUpHandlerRef = function (evt) {
  86510. _this._onPointerUp(evt);
  86511. };
  86512. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  86513. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  86514. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  86515. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  86516. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  86517. evt.preventDefault(); // Disables system menu
  86518. }, false);
  86519. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86520. }
  86521. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  86522. this._joystickSensibility = newJoystickSensibility;
  86523. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86524. };
  86525. VirtualJoystick.prototype._onPointerDown = function (e) {
  86526. var positionOnScreenCondition;
  86527. e.preventDefault();
  86528. if (this._leftJoystick === true) {
  86529. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  86530. }
  86531. else {
  86532. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  86533. }
  86534. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  86535. // First contact will be dedicated to the virtual joystick
  86536. this._joystickPointerID = e.pointerId;
  86537. this._joystickPointerStartPos.x = e.clientX;
  86538. this._joystickPointerStartPos.y = e.clientY;
  86539. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  86540. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  86541. this._deltaJoystickVector.x = 0;
  86542. this._deltaJoystickVector.y = 0;
  86543. this.pressed = true;
  86544. this._touches.add(e.pointerId.toString(), e);
  86545. }
  86546. else {
  86547. // You can only trigger the action buttons with a joystick declared
  86548. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  86549. this._action();
  86550. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  86551. }
  86552. }
  86553. };
  86554. VirtualJoystick.prototype._onPointerMove = function (e) {
  86555. // If the current pointer is the one associated to the joystick (first touch contact)
  86556. if (this._joystickPointerID == e.pointerId) {
  86557. this._joystickPointerPos.x = e.clientX;
  86558. this._joystickPointerPos.y = e.clientY;
  86559. this._deltaJoystickVector = this._joystickPointerPos.clone();
  86560. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  86561. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  86562. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  86563. switch (this._axisTargetedByLeftAndRight) {
  86564. case JoystickAxis.X:
  86565. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  86566. break;
  86567. case JoystickAxis.Y:
  86568. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  86569. break;
  86570. case JoystickAxis.Z:
  86571. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  86572. break;
  86573. }
  86574. var directionUpDown = this.reverseUpDown ? 1 : -1;
  86575. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  86576. switch (this._axisTargetedByUpAndDown) {
  86577. case JoystickAxis.X:
  86578. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  86579. break;
  86580. case JoystickAxis.Y:
  86581. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  86582. break;
  86583. case JoystickAxis.Z:
  86584. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  86585. break;
  86586. }
  86587. }
  86588. else {
  86589. var data = this._touches.get(e.pointerId.toString());
  86590. if (data) {
  86591. data.x = e.clientX;
  86592. data.y = e.clientY;
  86593. }
  86594. }
  86595. };
  86596. VirtualJoystick.prototype._onPointerUp = function (e) {
  86597. if (this._joystickPointerID == e.pointerId) {
  86598. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  86599. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  86600. this._joystickPointerID = -1;
  86601. this.pressed = false;
  86602. }
  86603. else {
  86604. var touch = this._touches.get(e.pointerId.toString());
  86605. if (touch) {
  86606. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  86607. }
  86608. }
  86609. this._deltaJoystickVector.x = 0;
  86610. this._deltaJoystickVector.y = 0;
  86611. this._touches.remove(e.pointerId.toString());
  86612. };
  86613. /**
  86614. * Change the color of the virtual joystick
  86615. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  86616. */
  86617. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  86618. this._joystickColor = newColor;
  86619. };
  86620. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  86621. this._action = action;
  86622. };
  86623. // Define which axis you'd like to control for left & right
  86624. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  86625. switch (axis) {
  86626. case JoystickAxis.X:
  86627. case JoystickAxis.Y:
  86628. case JoystickAxis.Z:
  86629. this._axisTargetedByLeftAndRight = axis;
  86630. break;
  86631. default:
  86632. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86633. break;
  86634. }
  86635. };
  86636. // Define which axis you'd like to control for up & down
  86637. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  86638. switch (axis) {
  86639. case JoystickAxis.X:
  86640. case JoystickAxis.Y:
  86641. case JoystickAxis.Z:
  86642. this._axisTargetedByUpAndDown = axis;
  86643. break;
  86644. default:
  86645. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86646. break;
  86647. }
  86648. };
  86649. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  86650. var _this = this;
  86651. if (this.pressed) {
  86652. this._touches.forEach(function (key, touch) {
  86653. if (touch.pointerId === _this._joystickPointerID) {
  86654. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  86655. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  86656. VirtualJoystick.vjCanvasContext.beginPath();
  86657. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  86658. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86659. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  86660. VirtualJoystick.vjCanvasContext.stroke();
  86661. VirtualJoystick.vjCanvasContext.closePath();
  86662. VirtualJoystick.vjCanvasContext.beginPath();
  86663. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86664. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86665. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  86666. VirtualJoystick.vjCanvasContext.stroke();
  86667. VirtualJoystick.vjCanvasContext.closePath();
  86668. VirtualJoystick.vjCanvasContext.beginPath();
  86669. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86670. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  86671. VirtualJoystick.vjCanvasContext.stroke();
  86672. VirtualJoystick.vjCanvasContext.closePath();
  86673. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  86674. }
  86675. else {
  86676. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  86677. VirtualJoystick.vjCanvasContext.beginPath();
  86678. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  86679. VirtualJoystick.vjCanvasContext.beginPath();
  86680. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  86681. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  86682. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  86683. VirtualJoystick.vjCanvasContext.stroke();
  86684. VirtualJoystick.vjCanvasContext.closePath();
  86685. touch.prevX = touch.x;
  86686. touch.prevY = touch.y;
  86687. }
  86688. ;
  86689. });
  86690. }
  86691. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86692. };
  86693. VirtualJoystick.prototype.releaseCanvas = function () {
  86694. if (VirtualJoystick.vjCanvas) {
  86695. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  86696. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  86697. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  86698. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  86699. window.removeEventListener("resize", this._onResize);
  86700. document.body.removeChild(VirtualJoystick.vjCanvas);
  86701. VirtualJoystick.vjCanvas = null;
  86702. }
  86703. };
  86704. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  86705. VirtualJoystick._globalJoystickIndex = 0;
  86706. return VirtualJoystick;
  86707. }());
  86708. BABYLON.VirtualJoystick = VirtualJoystick;
  86709. })(BABYLON || (BABYLON = {}));
  86710. //# sourceMappingURL=babylon.virtualJoystick.js.map
  86711. "use strict";
  86712. var BABYLON;
  86713. (function (BABYLON) {
  86714. // We're mainly based on the logic defined into the FreeCamera code
  86715. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  86716. __extends(VirtualJoysticksCamera, _super);
  86717. function VirtualJoysticksCamera(name, position, scene) {
  86718. var _this = _super.call(this, name, position, scene) || this;
  86719. _this.inputs.addVirtualJoystick();
  86720. return _this;
  86721. }
  86722. VirtualJoysticksCamera.prototype.getClassName = function () {
  86723. return "VirtualJoysticksCamera";
  86724. };
  86725. return VirtualJoysticksCamera;
  86726. }(BABYLON.FreeCamera));
  86727. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  86728. })(BABYLON || (BABYLON = {}));
  86729. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  86730. "use strict";
  86731. var BABYLON;
  86732. (function (BABYLON) {
  86733. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  86734. function FreeCameraVirtualJoystickInput() {
  86735. }
  86736. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  86737. return this._leftjoystick;
  86738. };
  86739. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  86740. return this._rightjoystick;
  86741. };
  86742. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  86743. if (this._leftjoystick) {
  86744. var camera = this.camera;
  86745. var speed = camera._computeLocalCameraSpeed() * 50;
  86746. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  86747. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  86748. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  86749. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  86750. if (!this._leftjoystick.pressed) {
  86751. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  86752. }
  86753. if (!this._rightjoystick.pressed) {
  86754. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  86755. }
  86756. }
  86757. };
  86758. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  86759. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  86760. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  86761. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  86762. this._leftjoystick.setJoystickSensibility(0.15);
  86763. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  86764. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  86765. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  86766. this._rightjoystick.reverseUpDown = true;
  86767. this._rightjoystick.setJoystickSensibility(0.05);
  86768. this._rightjoystick.setJoystickColor("yellow");
  86769. };
  86770. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  86771. this._leftjoystick.releaseCanvas();
  86772. this._rightjoystick.releaseCanvas();
  86773. };
  86774. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  86775. return "FreeCameraVirtualJoystickInput";
  86776. };
  86777. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  86778. return "virtualJoystick";
  86779. };
  86780. return FreeCameraVirtualJoystickInput;
  86781. }());
  86782. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  86783. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  86784. })(BABYLON || (BABYLON = {}));
  86785. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  86786. "use strict";
  86787. var BABYLON;
  86788. (function (BABYLON) {
  86789. var SimplificationSettings = /** @class */ (function () {
  86790. function SimplificationSettings(quality, distance, optimizeMesh) {
  86791. this.quality = quality;
  86792. this.distance = distance;
  86793. this.optimizeMesh = optimizeMesh;
  86794. }
  86795. return SimplificationSettings;
  86796. }());
  86797. BABYLON.SimplificationSettings = SimplificationSettings;
  86798. var SimplificationQueue = /** @class */ (function () {
  86799. function SimplificationQueue() {
  86800. this.running = false;
  86801. this._simplificationArray = [];
  86802. }
  86803. SimplificationQueue.prototype.addTask = function (task) {
  86804. this._simplificationArray.push(task);
  86805. };
  86806. SimplificationQueue.prototype.executeNext = function () {
  86807. var task = this._simplificationArray.pop();
  86808. if (task) {
  86809. this.running = true;
  86810. this.runSimplification(task);
  86811. }
  86812. else {
  86813. this.running = false;
  86814. }
  86815. };
  86816. SimplificationQueue.prototype.runSimplification = function (task) {
  86817. var _this = this;
  86818. if (task.parallelProcessing) {
  86819. //parallel simplifier
  86820. task.settings.forEach(function (setting) {
  86821. var simplifier = _this.getSimplifier(task);
  86822. simplifier.simplify(setting, function (newMesh) {
  86823. task.mesh.addLODLevel(setting.distance, newMesh);
  86824. newMesh.isVisible = true;
  86825. //check if it is the last
  86826. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  86827. //all done, run the success callback.
  86828. task.successCallback();
  86829. }
  86830. _this.executeNext();
  86831. });
  86832. });
  86833. }
  86834. else {
  86835. //single simplifier.
  86836. var simplifier = this.getSimplifier(task);
  86837. var runDecimation = function (setting, callback) {
  86838. simplifier.simplify(setting, function (newMesh) {
  86839. task.mesh.addLODLevel(setting.distance, newMesh);
  86840. newMesh.isVisible = true;
  86841. //run the next quality level
  86842. callback();
  86843. });
  86844. };
  86845. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  86846. runDecimation(task.settings[loop.index], function () {
  86847. loop.executeNext();
  86848. });
  86849. }, function () {
  86850. //execution ended, run the success callback.
  86851. if (task.successCallback) {
  86852. task.successCallback();
  86853. }
  86854. _this.executeNext();
  86855. });
  86856. }
  86857. };
  86858. SimplificationQueue.prototype.getSimplifier = function (task) {
  86859. switch (task.simplificationType) {
  86860. case SimplificationType.QUADRATIC:
  86861. default:
  86862. return new QuadraticErrorSimplification(task.mesh);
  86863. }
  86864. };
  86865. return SimplificationQueue;
  86866. }());
  86867. BABYLON.SimplificationQueue = SimplificationQueue;
  86868. /**
  86869. * The implemented types of simplification.
  86870. * At the moment only Quadratic Error Decimation is implemented.
  86871. */
  86872. var SimplificationType;
  86873. (function (SimplificationType) {
  86874. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  86875. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  86876. var DecimationTriangle = /** @class */ (function () {
  86877. function DecimationTriangle(vertices) {
  86878. this.vertices = vertices;
  86879. this.error = new Array(4);
  86880. this.deleted = false;
  86881. this.isDirty = false;
  86882. this.deletePending = false;
  86883. this.borderFactor = 0;
  86884. }
  86885. return DecimationTriangle;
  86886. }());
  86887. BABYLON.DecimationTriangle = DecimationTriangle;
  86888. var DecimationVertex = /** @class */ (function () {
  86889. function DecimationVertex(position, id) {
  86890. this.position = position;
  86891. this.id = id;
  86892. this.isBorder = true;
  86893. this.q = new QuadraticMatrix();
  86894. this.triangleCount = 0;
  86895. this.triangleStart = 0;
  86896. this.originalOffsets = [];
  86897. }
  86898. DecimationVertex.prototype.updatePosition = function (newPosition) {
  86899. this.position.copyFrom(newPosition);
  86900. };
  86901. return DecimationVertex;
  86902. }());
  86903. BABYLON.DecimationVertex = DecimationVertex;
  86904. var QuadraticMatrix = /** @class */ (function () {
  86905. function QuadraticMatrix(data) {
  86906. this.data = new Array(10);
  86907. for (var i = 0; i < 10; ++i) {
  86908. if (data && data[i]) {
  86909. this.data[i] = data[i];
  86910. }
  86911. else {
  86912. this.data[i] = 0;
  86913. }
  86914. }
  86915. }
  86916. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  86917. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  86918. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  86919. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  86920. return det;
  86921. };
  86922. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  86923. for (var i = 0; i < 10; ++i) {
  86924. this.data[i] += matrix.data[i];
  86925. }
  86926. };
  86927. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  86928. for (var i = 0; i < 10; ++i) {
  86929. this.data[i] += data[i];
  86930. }
  86931. };
  86932. QuadraticMatrix.prototype.add = function (matrix) {
  86933. var m = new QuadraticMatrix();
  86934. for (var i = 0; i < 10; ++i) {
  86935. m.data[i] = this.data[i] + matrix.data[i];
  86936. }
  86937. return m;
  86938. };
  86939. QuadraticMatrix.FromData = function (a, b, c, d) {
  86940. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  86941. };
  86942. //returning an array to avoid garbage collection
  86943. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  86944. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  86945. };
  86946. return QuadraticMatrix;
  86947. }());
  86948. BABYLON.QuadraticMatrix = QuadraticMatrix;
  86949. var Reference = /** @class */ (function () {
  86950. function Reference(vertexId, triangleId) {
  86951. this.vertexId = vertexId;
  86952. this.triangleId = triangleId;
  86953. }
  86954. return Reference;
  86955. }());
  86956. BABYLON.Reference = Reference;
  86957. /**
  86958. * An implementation of the Quadratic Error simplification algorithm.
  86959. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  86960. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  86961. * @author RaananW
  86962. */
  86963. var QuadraticErrorSimplification = /** @class */ (function () {
  86964. function QuadraticErrorSimplification(_mesh) {
  86965. this._mesh = _mesh;
  86966. this.syncIterations = 5000;
  86967. this.aggressiveness = 7;
  86968. this.decimationIterations = 100;
  86969. this.boundingBoxEpsilon = BABYLON.Epsilon;
  86970. }
  86971. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  86972. var _this = this;
  86973. this.initDecimatedMesh();
  86974. //iterating through the submeshes array, one after the other.
  86975. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  86976. _this.initWithMesh(loop.index, function () {
  86977. _this.runDecimation(settings, loop.index, function () {
  86978. loop.executeNext();
  86979. });
  86980. }, settings.optimizeMesh);
  86981. }, function () {
  86982. setTimeout(function () {
  86983. successCallback(_this._reconstructedMesh);
  86984. }, 0);
  86985. });
  86986. };
  86987. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  86988. var _this = this;
  86989. var targetCount = ~~(this.triangles.length * settings.quality);
  86990. var deletedTriangles = 0;
  86991. var triangleCount = this.triangles.length;
  86992. var iterationFunction = function (iteration, callback) {
  86993. setTimeout(function () {
  86994. if (iteration % 5 === 0) {
  86995. _this.updateMesh(iteration === 0);
  86996. }
  86997. for (var i = 0; i < _this.triangles.length; ++i) {
  86998. _this.triangles[i].isDirty = false;
  86999. }
  87000. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  87001. var trianglesIterator = function (i) {
  87002. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  87003. var t = _this.triangles[tIdx];
  87004. if (!t)
  87005. return;
  87006. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  87007. return;
  87008. }
  87009. for (var j = 0; j < 3; ++j) {
  87010. if (t.error[j] < threshold) {
  87011. var deleted0 = [];
  87012. var deleted1 = [];
  87013. var v0 = t.vertices[j];
  87014. var v1 = t.vertices[(j + 1) % 3];
  87015. if (v0.isBorder || v1.isBorder)
  87016. continue;
  87017. var p = BABYLON.Vector3.Zero();
  87018. var n = BABYLON.Vector3.Zero();
  87019. var uv = BABYLON.Vector2.Zero();
  87020. var color = new BABYLON.Color4(0, 0, 0, 1);
  87021. _this.calculateError(v0, v1, p, n, uv, color);
  87022. var delTr = new Array();
  87023. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  87024. continue;
  87025. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  87026. continue;
  87027. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  87028. continue;
  87029. var uniqueArray = new Array();
  87030. delTr.forEach(function (deletedT) {
  87031. if (uniqueArray.indexOf(deletedT) === -1) {
  87032. deletedT.deletePending = true;
  87033. uniqueArray.push(deletedT);
  87034. }
  87035. });
  87036. if (uniqueArray.length % 2 !== 0) {
  87037. continue;
  87038. }
  87039. v0.q = v1.q.add(v0.q);
  87040. v0.updatePosition(p);
  87041. var tStart = _this.references.length;
  87042. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  87043. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  87044. var tCount = _this.references.length - tStart;
  87045. if (tCount <= v0.triangleCount) {
  87046. if (tCount) {
  87047. for (var c = 0; c < tCount; c++) {
  87048. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  87049. }
  87050. }
  87051. }
  87052. else {
  87053. v0.triangleStart = tStart;
  87054. }
  87055. v0.triangleCount = tCount;
  87056. break;
  87057. }
  87058. }
  87059. };
  87060. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  87061. }, 0);
  87062. };
  87063. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  87064. if (triangleCount - deletedTriangles <= targetCount)
  87065. loop.breakLoop();
  87066. else {
  87067. iterationFunction(loop.index, function () {
  87068. loop.executeNext();
  87069. });
  87070. }
  87071. }, function () {
  87072. setTimeout(function () {
  87073. //reconstruct this part of the mesh
  87074. _this.reconstructMesh(submeshIndex);
  87075. successCallback();
  87076. }, 0);
  87077. });
  87078. };
  87079. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  87080. var _this = this;
  87081. this.vertices = [];
  87082. this.triangles = [];
  87083. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  87084. var indices = this._mesh.getIndices();
  87085. var submesh = this._mesh.subMeshes[submeshIndex];
  87086. var findInVertices = function (positionToSearch) {
  87087. if (optimizeMesh) {
  87088. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  87089. if (_this.vertices[ii].position.equals(positionToSearch)) {
  87090. return _this.vertices[ii];
  87091. }
  87092. }
  87093. }
  87094. return null;
  87095. };
  87096. var vertexReferences = [];
  87097. var vertexInit = function (i) {
  87098. if (!positionData) {
  87099. return;
  87100. }
  87101. var offset = i + submesh.verticesStart;
  87102. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  87103. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  87104. vertex.originalOffsets.push(offset);
  87105. if (vertex.id === _this.vertices.length) {
  87106. _this.vertices.push(vertex);
  87107. }
  87108. vertexReferences.push(vertex.id);
  87109. };
  87110. //var totalVertices = mesh.getTotalVertices();
  87111. var totalVertices = submesh.verticesCount;
  87112. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  87113. var indicesInit = function (i) {
  87114. if (!indices) {
  87115. return;
  87116. }
  87117. var offset = (submesh.indexStart / 3) + i;
  87118. var pos = (offset * 3);
  87119. var i0 = indices[pos + 0];
  87120. var i1 = indices[pos + 1];
  87121. var i2 = indices[pos + 2];
  87122. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  87123. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  87124. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  87125. var triangle = new DecimationTriangle([v0, v1, v2]);
  87126. triangle.originalOffset = pos;
  87127. _this.triangles.push(triangle);
  87128. };
  87129. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  87130. _this.init(callback);
  87131. });
  87132. });
  87133. };
  87134. QuadraticErrorSimplification.prototype.init = function (callback) {
  87135. var _this = this;
  87136. var triangleInit1 = function (i) {
  87137. var t = _this.triangles[i];
  87138. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  87139. for (var j = 0; j < 3; j++) {
  87140. 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))));
  87141. }
  87142. };
  87143. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  87144. var triangleInit2 = function (i) {
  87145. var t = _this.triangles[i];
  87146. for (var j = 0; j < 3; ++j) {
  87147. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  87148. }
  87149. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87150. };
  87151. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  87152. callback();
  87153. });
  87154. });
  87155. };
  87156. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  87157. var newTriangles = [];
  87158. var i;
  87159. for (i = 0; i < this.vertices.length; ++i) {
  87160. this.vertices[i].triangleCount = 0;
  87161. }
  87162. var t;
  87163. var j;
  87164. for (i = 0; i < this.triangles.length; ++i) {
  87165. if (!this.triangles[i].deleted) {
  87166. t = this.triangles[i];
  87167. for (j = 0; j < 3; ++j) {
  87168. t.vertices[j].triangleCount = 1;
  87169. }
  87170. newTriangles.push(t);
  87171. }
  87172. }
  87173. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  87174. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  87175. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  87176. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  87177. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  87178. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87179. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  87180. var vertexCount = 0;
  87181. for (i = 0; i < this.vertices.length; ++i) {
  87182. var vertex = this.vertices[i];
  87183. vertex.id = vertexCount;
  87184. if (vertex.triangleCount) {
  87185. vertex.originalOffsets.forEach(function (originalOffset) {
  87186. if (!normalData) {
  87187. return;
  87188. }
  87189. newPositionData.push(vertex.position.x);
  87190. newPositionData.push(vertex.position.y);
  87191. newPositionData.push(vertex.position.z);
  87192. newNormalData.push(normalData[originalOffset * 3]);
  87193. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  87194. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  87195. if (uvs && uvs.length) {
  87196. newUVsData.push(uvs[(originalOffset * 2)]);
  87197. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  87198. }
  87199. else if (colorsData && colorsData.length) {
  87200. newColorsData.push(colorsData[(originalOffset * 4)]);
  87201. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  87202. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  87203. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  87204. }
  87205. ++vertexCount;
  87206. });
  87207. }
  87208. }
  87209. var startingIndex = this._reconstructedMesh.getTotalIndices();
  87210. var startingVertex = this._reconstructedMesh.getTotalVertices();
  87211. var submeshesArray = this._reconstructedMesh.subMeshes;
  87212. this._reconstructedMesh.subMeshes = [];
  87213. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  87214. var originalIndices = this._mesh.getIndices();
  87215. for (i = 0; i < newTriangles.length; ++i) {
  87216. t = newTriangles[i]; //now get the new referencing point for each vertex
  87217. [0, 1, 2].forEach(function (idx) {
  87218. var id = originalIndices[t.originalOffset + idx];
  87219. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  87220. if (offset < 0)
  87221. offset = 0;
  87222. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  87223. });
  87224. }
  87225. //overwriting the old vertex buffers and indices.
  87226. this._reconstructedMesh.setIndices(newIndicesArray);
  87227. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  87228. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  87229. if (newUVsData.length > 0)
  87230. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  87231. if (newColorsData.length > 0)
  87232. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  87233. //create submesh
  87234. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  87235. if (submeshIndex > 0) {
  87236. this._reconstructedMesh.subMeshes = [];
  87237. submeshesArray.forEach(function (submesh) {
  87238. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  87239. });
  87240. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  87241. }
  87242. };
  87243. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  87244. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  87245. this._reconstructedMesh.material = this._mesh.material;
  87246. this._reconstructedMesh.parent = this._mesh.parent;
  87247. this._reconstructedMesh.isVisible = false;
  87248. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  87249. };
  87250. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  87251. for (var i = 0; i < vertex1.triangleCount; ++i) {
  87252. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  87253. if (t.deleted)
  87254. continue;
  87255. var s = this.references[vertex1.triangleStart + i].vertexId;
  87256. var v1 = t.vertices[(s + 1) % 3];
  87257. var v2 = t.vertices[(s + 2) % 3];
  87258. if ((v1 === vertex2 || v2 === vertex2)) {
  87259. deletedArray[i] = true;
  87260. delTr.push(t);
  87261. continue;
  87262. }
  87263. var d1 = v1.position.subtract(point);
  87264. d1 = d1.normalize();
  87265. var d2 = v2.position.subtract(point);
  87266. d2 = d2.normalize();
  87267. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  87268. return true;
  87269. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  87270. deletedArray[i] = false;
  87271. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  87272. return true;
  87273. }
  87274. return false;
  87275. };
  87276. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  87277. var newDeleted = deletedTriangles;
  87278. for (var i = 0; i < vertex.triangleCount; ++i) {
  87279. var ref = this.references[vertex.triangleStart + i];
  87280. var t = this.triangles[ref.triangleId];
  87281. if (t.deleted)
  87282. continue;
  87283. if (deletedArray[i] && t.deletePending) {
  87284. t.deleted = true;
  87285. newDeleted++;
  87286. continue;
  87287. }
  87288. t.vertices[ref.vertexId] = origVertex;
  87289. t.isDirty = true;
  87290. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  87291. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  87292. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  87293. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87294. this.references.push(ref);
  87295. }
  87296. return newDeleted;
  87297. };
  87298. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  87299. for (var i = 0; i < this.vertices.length; ++i) {
  87300. var vCount = [];
  87301. var vId = [];
  87302. var v = this.vertices[i];
  87303. var j;
  87304. for (j = 0; j < v.triangleCount; ++j) {
  87305. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  87306. for (var ii = 0; ii < 3; ii++) {
  87307. var ofs = 0;
  87308. var vv = triangle.vertices[ii];
  87309. while (ofs < vCount.length) {
  87310. if (vId[ofs] === vv.id)
  87311. break;
  87312. ++ofs;
  87313. }
  87314. if (ofs === vCount.length) {
  87315. vCount.push(1);
  87316. vId.push(vv.id);
  87317. }
  87318. else {
  87319. vCount[ofs]++;
  87320. }
  87321. }
  87322. }
  87323. for (j = 0; j < vCount.length; ++j) {
  87324. if (vCount[j] === 1) {
  87325. this.vertices[vId[j]].isBorder = true;
  87326. }
  87327. else {
  87328. this.vertices[vId[j]].isBorder = false;
  87329. }
  87330. }
  87331. }
  87332. };
  87333. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  87334. if (identifyBorders === void 0) { identifyBorders = false; }
  87335. var i;
  87336. if (!identifyBorders) {
  87337. var newTrianglesVector = [];
  87338. for (i = 0; i < this.triangles.length; ++i) {
  87339. if (!this.triangles[i].deleted) {
  87340. newTrianglesVector.push(this.triangles[i]);
  87341. }
  87342. }
  87343. this.triangles = newTrianglesVector;
  87344. }
  87345. for (i = 0; i < this.vertices.length; ++i) {
  87346. this.vertices[i].triangleCount = 0;
  87347. this.vertices[i].triangleStart = 0;
  87348. }
  87349. var t;
  87350. var j;
  87351. var v;
  87352. for (i = 0; i < this.triangles.length; ++i) {
  87353. t = this.triangles[i];
  87354. for (j = 0; j < 3; ++j) {
  87355. v = t.vertices[j];
  87356. v.triangleCount++;
  87357. }
  87358. }
  87359. var tStart = 0;
  87360. for (i = 0; i < this.vertices.length; ++i) {
  87361. this.vertices[i].triangleStart = tStart;
  87362. tStart += this.vertices[i].triangleCount;
  87363. this.vertices[i].triangleCount = 0;
  87364. }
  87365. var newReferences = new Array(this.triangles.length * 3);
  87366. for (i = 0; i < this.triangles.length; ++i) {
  87367. t = this.triangles[i];
  87368. for (j = 0; j < 3; ++j) {
  87369. v = t.vertices[j];
  87370. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  87371. v.triangleCount++;
  87372. }
  87373. }
  87374. this.references = newReferences;
  87375. if (identifyBorders) {
  87376. this.identifyBorder();
  87377. }
  87378. };
  87379. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  87380. var x = point.x;
  87381. var y = point.y;
  87382. var z = point.z;
  87383. 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
  87384. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  87385. };
  87386. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  87387. var q = vertex1.q.add(vertex2.q);
  87388. var border = vertex1.isBorder && vertex2.isBorder;
  87389. var error = 0;
  87390. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  87391. if (qDet !== 0 && !border) {
  87392. if (!pointResult) {
  87393. pointResult = BABYLON.Vector3.Zero();
  87394. }
  87395. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  87396. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  87397. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  87398. error = this.vertexError(q, pointResult);
  87399. }
  87400. else {
  87401. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  87402. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  87403. var error1 = this.vertexError(q, vertex1.position);
  87404. var error2 = this.vertexError(q, vertex2.position);
  87405. var error3 = this.vertexError(q, p3);
  87406. error = Math.min(error1, error2, error3);
  87407. if (error === error1) {
  87408. if (pointResult) {
  87409. pointResult.copyFrom(vertex1.position);
  87410. }
  87411. }
  87412. else if (error === error2) {
  87413. if (pointResult) {
  87414. pointResult.copyFrom(vertex2.position);
  87415. }
  87416. }
  87417. else {
  87418. if (pointResult) {
  87419. pointResult.copyFrom(p3);
  87420. }
  87421. }
  87422. }
  87423. return error;
  87424. };
  87425. return QuadraticErrorSimplification;
  87426. }());
  87427. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  87428. })(BABYLON || (BABYLON = {}));
  87429. //# sourceMappingURL=babylon.meshSimplification.js.map
  87430. "use strict";
  87431. var BABYLON;
  87432. (function (BABYLON) {
  87433. var MeshLODLevel = /** @class */ (function () {
  87434. function MeshLODLevel(distance, mesh) {
  87435. this.distance = distance;
  87436. this.mesh = mesh;
  87437. }
  87438. return MeshLODLevel;
  87439. }());
  87440. BABYLON.MeshLODLevel = MeshLODLevel;
  87441. })(BABYLON || (BABYLON = {}));
  87442. //# sourceMappingURL=babylon.meshLODLevel.js.map
  87443. "use strict";
  87444. var BABYLON;
  87445. (function (BABYLON) {
  87446. /**
  87447. * Defines the root class used to create scene optimization to use with SceneOptimizer
  87448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87449. */
  87450. var SceneOptimization = /** @class */ (function () {
  87451. /**
  87452. * Creates the SceneOptimization object
  87453. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87454. * @param desc defines the description associated with the optimization
  87455. */
  87456. function SceneOptimization(
  87457. /**
  87458. * Defines the priority of this optimization (0 by default which means first in the list)
  87459. */
  87460. priority) {
  87461. if (priority === void 0) { priority = 0; }
  87462. this.priority = priority;
  87463. }
  87464. /**
  87465. * Gets a string describing the action executed by the current optimization
  87466. * @returns description string
  87467. */
  87468. SceneOptimization.prototype.getDescription = function () {
  87469. return "";
  87470. };
  87471. /**
  87472. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87473. * @param scene defines the current scene where to apply this optimization
  87474. * @param optimizer defines the current optimizer
  87475. * @returns true if everything that can be done was applied
  87476. */
  87477. SceneOptimization.prototype.apply = function (scene, optimizer) {
  87478. return true;
  87479. };
  87480. ;
  87481. return SceneOptimization;
  87482. }());
  87483. BABYLON.SceneOptimization = SceneOptimization;
  87484. /**
  87485. * Defines an optimization used to reduce the size of render target textures
  87486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87487. */
  87488. var TextureOptimization = /** @class */ (function (_super) {
  87489. __extends(TextureOptimization, _super);
  87490. /**
  87491. * Creates the TextureOptimization object
  87492. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87493. * @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
  87494. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87495. */
  87496. function TextureOptimization(
  87497. /**
  87498. * Defines the priority of this optimization (0 by default which means first in the list)
  87499. */
  87500. priority,
  87501. /**
  87502. * 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
  87503. */
  87504. maximumSize,
  87505. /**
  87506. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87507. */
  87508. step) {
  87509. if (priority === void 0) { priority = 0; }
  87510. if (maximumSize === void 0) { maximumSize = 1024; }
  87511. if (step === void 0) { step = 0.5; }
  87512. var _this = _super.call(this, priority) || this;
  87513. _this.priority = priority;
  87514. _this.maximumSize = maximumSize;
  87515. _this.step = step;
  87516. return _this;
  87517. }
  87518. /**
  87519. * Gets a string describing the action executed by the current optimization
  87520. * @returns description string
  87521. */
  87522. TextureOptimization.prototype.getDescription = function () {
  87523. return "Reducing render target texture size to " + this.maximumSize;
  87524. };
  87525. /**
  87526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87527. * @param scene defines the current scene where to apply this optimization
  87528. * @param optimizer defines the current optimizer
  87529. * @returns true if everything that can be done was applied
  87530. */
  87531. TextureOptimization.prototype.apply = function (scene, optimizer) {
  87532. var allDone = true;
  87533. for (var index = 0; index < scene.textures.length; index++) {
  87534. var texture = scene.textures[index];
  87535. if (!texture.canRescale || texture.getContext) {
  87536. continue;
  87537. }
  87538. var currentSize = texture.getSize();
  87539. var maxDimension = Math.max(currentSize.width, currentSize.height);
  87540. if (maxDimension > this.maximumSize) {
  87541. texture.scale(this.step);
  87542. allDone = false;
  87543. }
  87544. }
  87545. return allDone;
  87546. };
  87547. return TextureOptimization;
  87548. }(SceneOptimization));
  87549. BABYLON.TextureOptimization = TextureOptimization;
  87550. /**
  87551. * Defines an optimization used to increase or decrease the rendering resolution
  87552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87553. */
  87554. var HardwareScalingOptimization = /** @class */ (function (_super) {
  87555. __extends(HardwareScalingOptimization, _super);
  87556. /**
  87557. * Creates the HardwareScalingOptimization object
  87558. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87559. * @param maximumScale defines the maximum scale to use (2 by default)
  87560. * @param step defines the step to use between two passes (0.5 by default)
  87561. */
  87562. function HardwareScalingOptimization(
  87563. /**
  87564. * Defines the priority of this optimization (0 by default which means first in the list)
  87565. */
  87566. priority,
  87567. /**
  87568. * Defines the maximum scale to use (2 by default)
  87569. */
  87570. maximumScale,
  87571. /**
  87572. * Defines the step to use between two passes (0.5 by default)
  87573. */
  87574. step) {
  87575. if (priority === void 0) { priority = 0; }
  87576. if (maximumScale === void 0) { maximumScale = 2; }
  87577. if (step === void 0) { step = 0.25; }
  87578. var _this = _super.call(this, priority) || this;
  87579. _this.priority = priority;
  87580. _this.maximumScale = maximumScale;
  87581. _this.step = step;
  87582. _this._currentScale = -1;
  87583. _this._directionOffset = 1;
  87584. return _this;
  87585. }
  87586. /**
  87587. * Gets a string describing the action executed by the current optimization
  87588. * @return description string
  87589. */
  87590. HardwareScalingOptimization.prototype.getDescription = function () {
  87591. return "Setting hardware scaling level to " + this._currentScale;
  87592. };
  87593. /**
  87594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87595. * @param scene defines the current scene where to apply this optimization
  87596. * @param optimizer defines the current optimizer
  87597. * @returns true if everything that can be done was applied
  87598. */
  87599. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  87600. if (this._currentScale === -1) {
  87601. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  87602. if (this._currentScale > this.maximumScale) {
  87603. this._directionOffset = -1;
  87604. }
  87605. }
  87606. this._currentScale += this._directionOffset * this.step;
  87607. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  87608. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  87609. };
  87610. ;
  87611. return HardwareScalingOptimization;
  87612. }(SceneOptimization));
  87613. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  87614. /**
  87615. * Defines an optimization used to remove shadows
  87616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87617. */
  87618. var ShadowsOptimization = /** @class */ (function (_super) {
  87619. __extends(ShadowsOptimization, _super);
  87620. function ShadowsOptimization() {
  87621. return _super !== null && _super.apply(this, arguments) || this;
  87622. }
  87623. /**
  87624. * Gets a string describing the action executed by the current optimization
  87625. * @return description string
  87626. */
  87627. ShadowsOptimization.prototype.getDescription = function () {
  87628. return "Turning shadows on/off";
  87629. };
  87630. /**
  87631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87632. * @param scene defines the current scene where to apply this optimization
  87633. * @param optimizer defines the current optimizer
  87634. * @returns true if everything that can be done was applied
  87635. */
  87636. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  87637. scene.shadowsEnabled = optimizer.isInImprovementMode;
  87638. return true;
  87639. };
  87640. ;
  87641. return ShadowsOptimization;
  87642. }(SceneOptimization));
  87643. BABYLON.ShadowsOptimization = ShadowsOptimization;
  87644. /**
  87645. * Defines an optimization used to turn post-processes off
  87646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87647. */
  87648. var PostProcessesOptimization = /** @class */ (function (_super) {
  87649. __extends(PostProcessesOptimization, _super);
  87650. function PostProcessesOptimization() {
  87651. return _super !== null && _super.apply(this, arguments) || this;
  87652. }
  87653. /**
  87654. * Gets a string describing the action executed by the current optimization
  87655. * @return description string
  87656. */
  87657. PostProcessesOptimization.prototype.getDescription = function () {
  87658. return "Turning post-processes on/off";
  87659. };
  87660. /**
  87661. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87662. * @param scene defines the current scene where to apply this optimization
  87663. * @param optimizer defines the current optimizer
  87664. * @returns true if everything that can be done was applied
  87665. */
  87666. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  87667. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  87668. return true;
  87669. };
  87670. ;
  87671. return PostProcessesOptimization;
  87672. }(SceneOptimization));
  87673. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  87674. /**
  87675. * Defines an optimization used to turn lens flares off
  87676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87677. */
  87678. var LensFlaresOptimization = /** @class */ (function (_super) {
  87679. __extends(LensFlaresOptimization, _super);
  87680. function LensFlaresOptimization() {
  87681. return _super !== null && _super.apply(this, arguments) || this;
  87682. }
  87683. /**
  87684. * Gets a string describing the action executed by the current optimization
  87685. * @return description string
  87686. */
  87687. LensFlaresOptimization.prototype.getDescription = function () {
  87688. return "Turning lens flares on/off";
  87689. };
  87690. /**
  87691. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87692. * @param scene defines the current scene where to apply this optimization
  87693. * @param optimizer defines the current optimizer
  87694. * @returns true if everything that can be done was applied
  87695. */
  87696. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  87697. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  87698. return true;
  87699. };
  87700. ;
  87701. return LensFlaresOptimization;
  87702. }(SceneOptimization));
  87703. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  87704. /**
  87705. * Defines an optimization based on user defined callback.
  87706. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87707. */
  87708. var CustomOptimization = /** @class */ (function (_super) {
  87709. __extends(CustomOptimization, _super);
  87710. function CustomOptimization() {
  87711. return _super !== null && _super.apply(this, arguments) || this;
  87712. }
  87713. /**
  87714. * Gets a string describing the action executed by the current optimization
  87715. * @returns description string
  87716. */
  87717. CustomOptimization.prototype.getDescription = function () {
  87718. if (this.onGetDescription) {
  87719. return this.onGetDescription();
  87720. }
  87721. return "Running user defined callback";
  87722. };
  87723. /**
  87724. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87725. * @param scene defines the current scene where to apply this optimization
  87726. * @param optimizer defines the current optimizer
  87727. * @returns true if everything that can be done was applied
  87728. */
  87729. CustomOptimization.prototype.apply = function (scene, optimizer) {
  87730. if (this.onApply) {
  87731. return this.onApply(scene, optimizer);
  87732. }
  87733. return true;
  87734. };
  87735. ;
  87736. return CustomOptimization;
  87737. }(SceneOptimization));
  87738. BABYLON.CustomOptimization = CustomOptimization;
  87739. /**
  87740. * Defines an optimization used to turn particles off
  87741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87742. */
  87743. var ParticlesOptimization = /** @class */ (function (_super) {
  87744. __extends(ParticlesOptimization, _super);
  87745. function ParticlesOptimization() {
  87746. return _super !== null && _super.apply(this, arguments) || this;
  87747. }
  87748. /**
  87749. * Gets a string describing the action executed by the current optimization
  87750. * @return description string
  87751. */
  87752. ParticlesOptimization.prototype.getDescription = function () {
  87753. return "Turning particles on/off";
  87754. };
  87755. /**
  87756. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87757. * @param scene defines the current scene where to apply this optimization
  87758. * @param optimizer defines the current optimizer
  87759. * @returns true if everything that can be done was applied
  87760. */
  87761. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  87762. scene.particlesEnabled = optimizer.isInImprovementMode;
  87763. return true;
  87764. };
  87765. ;
  87766. return ParticlesOptimization;
  87767. }(SceneOptimization));
  87768. BABYLON.ParticlesOptimization = ParticlesOptimization;
  87769. /**
  87770. * Defines an optimization used to turn render targets off
  87771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87772. */
  87773. var RenderTargetsOptimization = /** @class */ (function (_super) {
  87774. __extends(RenderTargetsOptimization, _super);
  87775. function RenderTargetsOptimization() {
  87776. return _super !== null && _super.apply(this, arguments) || this;
  87777. }
  87778. /**
  87779. * Gets a string describing the action executed by the current optimization
  87780. * @return description string
  87781. */
  87782. RenderTargetsOptimization.prototype.getDescription = function () {
  87783. return "Turning render targets off";
  87784. };
  87785. /**
  87786. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87787. * @param scene defines the current scene where to apply this optimization
  87788. * @param optimizer defines the current optimizer
  87789. * @returns true if everything that can be done was applied
  87790. */
  87791. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  87792. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  87793. return true;
  87794. };
  87795. ;
  87796. return RenderTargetsOptimization;
  87797. }(SceneOptimization));
  87798. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  87799. /**
  87800. * Defines an optimization used to merge meshes with compatible materials
  87801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87802. */
  87803. var MergeMeshesOptimization = /** @class */ (function (_super) {
  87804. __extends(MergeMeshesOptimization, _super);
  87805. function MergeMeshesOptimization() {
  87806. var _this = _super !== null && _super.apply(this, arguments) || this;
  87807. _this._canBeMerged = function (abstractMesh) {
  87808. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  87809. return false;
  87810. }
  87811. var mesh = abstractMesh;
  87812. if (!mesh.isVisible || !mesh.isEnabled()) {
  87813. return false;
  87814. }
  87815. if (mesh.instances.length > 0) {
  87816. return false;
  87817. }
  87818. if (mesh.skeleton || mesh.hasLODLevels) {
  87819. return false;
  87820. }
  87821. if (mesh.parent) {
  87822. return false;
  87823. }
  87824. return true;
  87825. };
  87826. return _this;
  87827. }
  87828. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  87829. /**
  87830. * Gets or sets a boolean which defines if optimization octree has to be updated
  87831. */
  87832. get: function () {
  87833. return MergeMeshesOptimization._UpdateSelectionTree;
  87834. },
  87835. /**
  87836. * Gets or sets a boolean which defines if optimization octree has to be updated
  87837. */
  87838. set: function (value) {
  87839. MergeMeshesOptimization._UpdateSelectionTree = value;
  87840. },
  87841. enumerable: true,
  87842. configurable: true
  87843. });
  87844. /**
  87845. * Gets a string describing the action executed by the current optimization
  87846. * @return description string
  87847. */
  87848. MergeMeshesOptimization.prototype.getDescription = function () {
  87849. return "Merging similar meshes together";
  87850. };
  87851. /**
  87852. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87853. * @param scene defines the current scene where to apply this optimization
  87854. * @param optimizer defines the current optimizer
  87855. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  87856. * @returns true if everything that can be done was applied
  87857. */
  87858. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  87859. var globalPool = scene.meshes.slice(0);
  87860. var globalLength = globalPool.length;
  87861. for (var index = 0; index < globalLength; index++) {
  87862. var currentPool = new Array();
  87863. var current = globalPool[index];
  87864. // Checks
  87865. if (!this._canBeMerged(current)) {
  87866. continue;
  87867. }
  87868. currentPool.push(current);
  87869. // Find compatible meshes
  87870. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  87871. var otherMesh = globalPool[subIndex];
  87872. if (!this._canBeMerged(otherMesh)) {
  87873. continue;
  87874. }
  87875. if (otherMesh.material !== current.material) {
  87876. continue;
  87877. }
  87878. if (otherMesh.checkCollisions !== current.checkCollisions) {
  87879. continue;
  87880. }
  87881. currentPool.push(otherMesh);
  87882. globalLength--;
  87883. globalPool.splice(subIndex, 1);
  87884. subIndex--;
  87885. }
  87886. if (currentPool.length < 2) {
  87887. continue;
  87888. }
  87889. // Merge meshes
  87890. BABYLON.Mesh.MergeMeshes(currentPool);
  87891. }
  87892. if (updateSelectionTree != undefined) {
  87893. if (updateSelectionTree) {
  87894. scene.createOrUpdateSelectionOctree();
  87895. }
  87896. }
  87897. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  87898. scene.createOrUpdateSelectionOctree();
  87899. }
  87900. return true;
  87901. };
  87902. ;
  87903. MergeMeshesOptimization._UpdateSelectionTree = false;
  87904. return MergeMeshesOptimization;
  87905. }(SceneOptimization));
  87906. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  87907. /**
  87908. * Defines a list of options used by SceneOptimizer
  87909. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87910. */
  87911. var SceneOptimizerOptions = /** @class */ (function () {
  87912. /**
  87913. * Creates a new list of options used by SceneOptimizer
  87914. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  87915. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  87916. */
  87917. function SceneOptimizerOptions(
  87918. /**
  87919. * Defines the target frame rate to reach (60 by default)
  87920. */
  87921. targetFrameRate,
  87922. /**
  87923. * Defines the interval between two checkes (2000ms by default)
  87924. */
  87925. trackerDuration) {
  87926. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  87927. if (trackerDuration === void 0) { trackerDuration = 2000; }
  87928. this.targetFrameRate = targetFrameRate;
  87929. this.trackerDuration = trackerDuration;
  87930. /**
  87931. * Gets the list of optimizations to apply
  87932. */
  87933. this.optimizations = new Array();
  87934. }
  87935. /**
  87936. * Add a new optimization
  87937. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  87938. * @returns the current SceneOptimizerOptions
  87939. */
  87940. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  87941. this.optimizations.push(optimization);
  87942. return this;
  87943. };
  87944. /**
  87945. * Add a new custom optimization
  87946. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  87947. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  87948. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87949. * @returns the current SceneOptimizerOptions
  87950. */
  87951. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  87952. if (priority === void 0) { priority = 0; }
  87953. var optimization = new CustomOptimization(priority);
  87954. optimization.onApply = onApply;
  87955. optimization.onGetDescription = onGetDescription;
  87956. this.optimizations.push(optimization);
  87957. return this;
  87958. };
  87959. /**
  87960. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  87961. * @param targetFrameRate defines the target frame rate (60 by default)
  87962. * @returns a SceneOptimizerOptions object
  87963. */
  87964. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  87965. var result = new SceneOptimizerOptions(targetFrameRate);
  87966. var priority = 0;
  87967. result.addOptimization(new MergeMeshesOptimization(priority));
  87968. result.addOptimization(new ShadowsOptimization(priority));
  87969. result.addOptimization(new LensFlaresOptimization(priority));
  87970. // Next priority
  87971. priority++;
  87972. result.addOptimization(new PostProcessesOptimization(priority));
  87973. result.addOptimization(new ParticlesOptimization(priority));
  87974. // Next priority
  87975. priority++;
  87976. result.addOptimization(new TextureOptimization(priority, 1024));
  87977. return result;
  87978. };
  87979. /**
  87980. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  87981. * @param targetFrameRate defines the target frame rate (60 by default)
  87982. * @returns a SceneOptimizerOptions object
  87983. */
  87984. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  87985. var result = new SceneOptimizerOptions(targetFrameRate);
  87986. var priority = 0;
  87987. result.addOptimization(new MergeMeshesOptimization(priority));
  87988. result.addOptimization(new ShadowsOptimization(priority));
  87989. result.addOptimization(new LensFlaresOptimization(priority));
  87990. // Next priority
  87991. priority++;
  87992. result.addOptimization(new PostProcessesOptimization(priority));
  87993. result.addOptimization(new ParticlesOptimization(priority));
  87994. // Next priority
  87995. priority++;
  87996. result.addOptimization(new TextureOptimization(priority, 512));
  87997. // Next priority
  87998. priority++;
  87999. result.addOptimization(new RenderTargetsOptimization(priority));
  88000. // Next priority
  88001. priority++;
  88002. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  88003. return result;
  88004. };
  88005. /**
  88006. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  88007. * @param targetFrameRate defines the target frame rate (60 by default)
  88008. * @returns a SceneOptimizerOptions object
  88009. */
  88010. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  88011. var result = new SceneOptimizerOptions(targetFrameRate);
  88012. var priority = 0;
  88013. result.addOptimization(new MergeMeshesOptimization(priority));
  88014. result.addOptimization(new ShadowsOptimization(priority));
  88015. result.addOptimization(new LensFlaresOptimization(priority));
  88016. // Next priority
  88017. priority++;
  88018. result.addOptimization(new PostProcessesOptimization(priority));
  88019. result.addOptimization(new ParticlesOptimization(priority));
  88020. // Next priority
  88021. priority++;
  88022. result.addOptimization(new TextureOptimization(priority, 256));
  88023. // Next priority
  88024. priority++;
  88025. result.addOptimization(new RenderTargetsOptimization(priority));
  88026. // Next priority
  88027. priority++;
  88028. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  88029. return result;
  88030. };
  88031. return SceneOptimizerOptions;
  88032. }());
  88033. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  88034. /**
  88035. * Class used to run optimizations in order to reach a target frame rate
  88036. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88037. */
  88038. var SceneOptimizer = /** @class */ (function () {
  88039. /**
  88040. * Creates a new SceneOptimizer
  88041. * @param scene defines the scene to work on
  88042. * @param options defines the options to use with the SceneOptimizer
  88043. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  88044. * @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)
  88045. */
  88046. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  88047. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  88048. if (improvementMode === void 0) { improvementMode = false; }
  88049. var _this = this;
  88050. this._isRunning = false;
  88051. this._currentPriorityLevel = 0;
  88052. this._targetFrameRate = 60;
  88053. this._trackerDuration = 2000;
  88054. this._currentFrameRate = 0;
  88055. this._improvementMode = false;
  88056. /**
  88057. * Defines an observable called when the optimizer reaches the target frame rate
  88058. */
  88059. this.onSuccessObservable = new BABYLON.Observable();
  88060. /**
  88061. * Defines an observable called when the optimizer enables an optimization
  88062. */
  88063. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  88064. /**
  88065. * Defines an observable called when the optimizer is not able to reach the target frame rate
  88066. */
  88067. this.onFailureObservable = new BABYLON.Observable();
  88068. if (!options) {
  88069. this._options = new SceneOptimizerOptions();
  88070. }
  88071. else {
  88072. this._options = options;
  88073. }
  88074. if (this._options.targetFrameRate) {
  88075. this._targetFrameRate = this._options.targetFrameRate;
  88076. }
  88077. if (this._options.trackerDuration) {
  88078. this._trackerDuration = this._options.trackerDuration;
  88079. }
  88080. if (autoGeneratePriorities) {
  88081. var priority = 0;
  88082. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  88083. var optim = _a[_i];
  88084. optim.priority = priority++;
  88085. }
  88086. }
  88087. this._improvementMode = improvementMode;
  88088. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88089. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  88090. _this._sceneDisposeObserver = null;
  88091. _this.dispose();
  88092. });
  88093. }
  88094. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  88095. /**
  88096. * Gets a boolean indicating if the optimizer is in improvement mode
  88097. */
  88098. get: function () {
  88099. return this._improvementMode;
  88100. },
  88101. enumerable: true,
  88102. configurable: true
  88103. });
  88104. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  88105. /**
  88106. * Gets the current priority level (0 at start)
  88107. */
  88108. get: function () {
  88109. return this._currentPriorityLevel;
  88110. },
  88111. enumerable: true,
  88112. configurable: true
  88113. });
  88114. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  88115. /**
  88116. * Gets the current frame rate checked by the SceneOptimizer
  88117. */
  88118. get: function () {
  88119. return this._currentFrameRate;
  88120. },
  88121. enumerable: true,
  88122. configurable: true
  88123. });
  88124. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  88125. /**
  88126. * Gets or sets the current target frame rate (60 by default)
  88127. */
  88128. get: function () {
  88129. return this._targetFrameRate;
  88130. },
  88131. /**
  88132. * Gets or sets the current target frame rate (60 by default)
  88133. */
  88134. set: function (value) {
  88135. this._targetFrameRate = value;
  88136. },
  88137. enumerable: true,
  88138. configurable: true
  88139. });
  88140. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  88141. /**
  88142. * Gets or sets the current interval between two checks (every 2000ms by default)
  88143. */
  88144. get: function () {
  88145. return this._trackerDuration;
  88146. },
  88147. /**
  88148. * Gets or sets the current interval between two checks (every 2000ms by default)
  88149. */
  88150. set: function (value) {
  88151. this._trackerDuration = value;
  88152. },
  88153. enumerable: true,
  88154. configurable: true
  88155. });
  88156. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  88157. /**
  88158. * Gets the list of active optimizations
  88159. */
  88160. get: function () {
  88161. return this._options.optimizations;
  88162. },
  88163. enumerable: true,
  88164. configurable: true
  88165. });
  88166. /**
  88167. * Stops the current optimizer
  88168. */
  88169. SceneOptimizer.prototype.stop = function () {
  88170. this._isRunning = false;
  88171. };
  88172. /**
  88173. * Reset the optimizer to initial step (current priority level = 0)
  88174. */
  88175. SceneOptimizer.prototype.reset = function () {
  88176. this._currentPriorityLevel = 0;
  88177. };
  88178. /**
  88179. * Start the optimizer. By default it will try to reach a specific framerate
  88180. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  88181. */
  88182. SceneOptimizer.prototype.start = function () {
  88183. var _this = this;
  88184. if (this._isRunning) {
  88185. return;
  88186. }
  88187. this._isRunning = true;
  88188. // Let's wait for the scene to be ready before running our check
  88189. this._scene.executeWhenReady(function () {
  88190. setTimeout(function () {
  88191. _this._checkCurrentState();
  88192. }, _this._trackerDuration);
  88193. });
  88194. };
  88195. SceneOptimizer.prototype._checkCurrentState = function () {
  88196. var _this = this;
  88197. if (!this._isRunning) {
  88198. return;
  88199. }
  88200. var scene = this._scene;
  88201. var options = this._options;
  88202. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  88203. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  88204. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  88205. this._isRunning = false;
  88206. this.onSuccessObservable.notifyObservers(this);
  88207. return;
  88208. }
  88209. // Apply current level of optimizations
  88210. var allDone = true;
  88211. var noOptimizationApplied = true;
  88212. for (var index = 0; index < options.optimizations.length; index++) {
  88213. var optimization = options.optimizations[index];
  88214. if (optimization.priority === this._currentPriorityLevel) {
  88215. noOptimizationApplied = false;
  88216. allDone = allDone && optimization.apply(scene, this);
  88217. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  88218. }
  88219. }
  88220. // If no optimization was applied, this is a failure :(
  88221. if (noOptimizationApplied) {
  88222. this._isRunning = false;
  88223. this.onFailureObservable.notifyObservers(this);
  88224. return;
  88225. }
  88226. // If all optimizations were done, move to next level
  88227. if (allDone) {
  88228. this._currentPriorityLevel++;
  88229. }
  88230. // Let's the system running for a specific amount of time before checking FPS
  88231. scene.executeWhenReady(function () {
  88232. setTimeout(function () {
  88233. _this._checkCurrentState();
  88234. }, _this._trackerDuration);
  88235. });
  88236. };
  88237. /**
  88238. * Release all resources
  88239. */
  88240. SceneOptimizer.prototype.dispose = function () {
  88241. this.stop();
  88242. this.onSuccessObservable.clear();
  88243. this.onFailureObservable.clear();
  88244. this.onNewOptimizationAppliedObservable.clear();
  88245. if (this._sceneDisposeObserver) {
  88246. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88247. }
  88248. };
  88249. /**
  88250. * Helper function to create a SceneOptimizer with one single line of code
  88251. * @param scene defines the scene to work on
  88252. * @param options defines the options to use with the SceneOptimizer
  88253. * @param onSuccess defines a callback to call on success
  88254. * @param onFailure defines a callback to call on failure
  88255. * @returns the new SceneOptimizer object
  88256. */
  88257. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  88258. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  88259. if (onSuccess) {
  88260. optimizer.onSuccessObservable.add(function () {
  88261. onSuccess();
  88262. });
  88263. }
  88264. if (onFailure) {
  88265. optimizer.onFailureObservable.add(function () {
  88266. onFailure();
  88267. });
  88268. }
  88269. optimizer.start();
  88270. return optimizer;
  88271. };
  88272. return SceneOptimizer;
  88273. }());
  88274. BABYLON.SceneOptimizer = SceneOptimizer;
  88275. })(BABYLON || (BABYLON = {}));
  88276. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  88277. "use strict";
  88278. var BABYLON;
  88279. (function (BABYLON) {
  88280. var OutlineRenderer = /** @class */ (function () {
  88281. function OutlineRenderer(scene) {
  88282. this.zOffset = 1;
  88283. this._scene = scene;
  88284. }
  88285. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  88286. var _this = this;
  88287. if (useOverlay === void 0) { useOverlay = false; }
  88288. var scene = this._scene;
  88289. var engine = this._scene.getEngine();
  88290. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88291. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  88292. return;
  88293. }
  88294. var mesh = subMesh.getRenderingMesh();
  88295. var material = subMesh.getMaterial();
  88296. if (!material || !scene.activeCamera) {
  88297. return;
  88298. }
  88299. engine.enableEffect(this._effect);
  88300. // Logarithmic depth
  88301. if (material.useLogarithmicDepth) {
  88302. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  88303. }
  88304. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  88305. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  88306. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  88307. // Bones
  88308. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88309. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88310. }
  88311. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  88312. // Alpha test
  88313. if (material && material.needAlphaTesting()) {
  88314. var alphaTexture = material.getAlphaTestTexture();
  88315. if (alphaTexture) {
  88316. this._effect.setTexture("diffuseSampler", alphaTexture);
  88317. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88318. }
  88319. }
  88320. engine.setZOffset(-this.zOffset);
  88321. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  88322. engine.setZOffset(0);
  88323. };
  88324. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  88325. var defines = [];
  88326. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88327. var mesh = subMesh.getMesh();
  88328. var material = subMesh.getMaterial();
  88329. if (material) {
  88330. // Alpha test
  88331. if (material.needAlphaTesting()) {
  88332. defines.push("#define ALPHATEST");
  88333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88334. attribs.push(BABYLON.VertexBuffer.UVKind);
  88335. defines.push("#define UV1");
  88336. }
  88337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88338. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88339. defines.push("#define UV2");
  88340. }
  88341. }
  88342. //Logarithmic depth
  88343. if (material.useLogarithmicDepth) {
  88344. defines.push("#define LOGARITHMICDEPTH");
  88345. }
  88346. }
  88347. // Bones
  88348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88351. if (mesh.numBoneInfluencers > 4) {
  88352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88354. }
  88355. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88356. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  88357. }
  88358. else {
  88359. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88360. }
  88361. // Instances
  88362. if (useInstances) {
  88363. defines.push("#define INSTANCES");
  88364. attribs.push("world0");
  88365. attribs.push("world1");
  88366. attribs.push("world2");
  88367. attribs.push("world3");
  88368. }
  88369. // Get correct effect
  88370. var join = defines.join("\n");
  88371. if (this._cachedDefines !== join) {
  88372. this._cachedDefines = join;
  88373. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  88374. }
  88375. return this._effect.isReady();
  88376. };
  88377. return OutlineRenderer;
  88378. }());
  88379. BABYLON.OutlineRenderer = OutlineRenderer;
  88380. })(BABYLON || (BABYLON = {}));
  88381. //# sourceMappingURL=babylon.outlineRenderer.js.map
  88382. "use strict";
  88383. var BABYLON;
  88384. (function (BABYLON) {
  88385. var FaceAdjacencies = /** @class */ (function () {
  88386. function FaceAdjacencies() {
  88387. this.edges = new Array();
  88388. this.edgesConnectedCount = 0;
  88389. }
  88390. return FaceAdjacencies;
  88391. }());
  88392. var EdgesRenderer = /** @class */ (function () {
  88393. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  88394. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  88395. if (epsilon === void 0) { epsilon = 0.95; }
  88396. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  88397. this.edgesWidthScalerForOrthographic = 1000.0;
  88398. this.edgesWidthScalerForPerspective = 50.0;
  88399. this._linesPositions = new Array();
  88400. this._linesNormals = new Array();
  88401. this._linesIndices = new Array();
  88402. this._buffers = {};
  88403. this._checkVerticesInsteadOfIndices = false;
  88404. this._source = source;
  88405. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  88406. this._epsilon = epsilon;
  88407. this._prepareRessources();
  88408. this._generateEdgesLines();
  88409. }
  88410. EdgesRenderer.prototype._prepareRessources = function () {
  88411. if (this._lineShader) {
  88412. return;
  88413. }
  88414. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  88415. attributes: ["position", "normal"],
  88416. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  88417. });
  88418. this._lineShader.disableDepthWrite = true;
  88419. this._lineShader.backFaceCulling = false;
  88420. };
  88421. EdgesRenderer.prototype._rebuild = function () {
  88422. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88423. if (buffer) {
  88424. buffer._rebuild();
  88425. }
  88426. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88427. if (buffer) {
  88428. buffer._rebuild();
  88429. }
  88430. var scene = this._source.getScene();
  88431. var engine = scene.getEngine();
  88432. this._ib = engine.createIndexBuffer(this._linesIndices);
  88433. };
  88434. EdgesRenderer.prototype.dispose = function () {
  88435. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88436. if (buffer) {
  88437. buffer.dispose();
  88438. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  88439. }
  88440. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88441. if (buffer) {
  88442. buffer.dispose();
  88443. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  88444. }
  88445. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  88446. this._lineShader.dispose();
  88447. };
  88448. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  88449. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  88450. return 0;
  88451. }
  88452. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  88453. return 1;
  88454. }
  88455. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  88456. return 2;
  88457. }
  88458. return -1;
  88459. };
  88460. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  88461. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  88462. return 0;
  88463. }
  88464. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  88465. return 1;
  88466. }
  88467. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  88468. return 2;
  88469. }
  88470. return -1;
  88471. };
  88472. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  88473. var needToCreateLine;
  88474. if (edge === undefined) {
  88475. needToCreateLine = true;
  88476. }
  88477. else {
  88478. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  88479. needToCreateLine = dotProduct < this._epsilon;
  88480. }
  88481. if (needToCreateLine) {
  88482. var offset = this._linesPositions.length / 3;
  88483. var normal = p0.subtract(p1);
  88484. normal.normalize();
  88485. // Positions
  88486. this._linesPositions.push(p0.x);
  88487. this._linesPositions.push(p0.y);
  88488. this._linesPositions.push(p0.z);
  88489. this._linesPositions.push(p0.x);
  88490. this._linesPositions.push(p0.y);
  88491. this._linesPositions.push(p0.z);
  88492. this._linesPositions.push(p1.x);
  88493. this._linesPositions.push(p1.y);
  88494. this._linesPositions.push(p1.z);
  88495. this._linesPositions.push(p1.x);
  88496. this._linesPositions.push(p1.y);
  88497. this._linesPositions.push(p1.z);
  88498. // Normals
  88499. this._linesNormals.push(p1.x);
  88500. this._linesNormals.push(p1.y);
  88501. this._linesNormals.push(p1.z);
  88502. this._linesNormals.push(-1);
  88503. this._linesNormals.push(p1.x);
  88504. this._linesNormals.push(p1.y);
  88505. this._linesNormals.push(p1.z);
  88506. this._linesNormals.push(1);
  88507. this._linesNormals.push(p0.x);
  88508. this._linesNormals.push(p0.y);
  88509. this._linesNormals.push(p0.z);
  88510. this._linesNormals.push(-1);
  88511. this._linesNormals.push(p0.x);
  88512. this._linesNormals.push(p0.y);
  88513. this._linesNormals.push(p0.z);
  88514. this._linesNormals.push(1);
  88515. // Indices
  88516. this._linesIndices.push(offset);
  88517. this._linesIndices.push(offset + 1);
  88518. this._linesIndices.push(offset + 2);
  88519. this._linesIndices.push(offset);
  88520. this._linesIndices.push(offset + 2);
  88521. this._linesIndices.push(offset + 3);
  88522. }
  88523. };
  88524. EdgesRenderer.prototype._generateEdgesLines = function () {
  88525. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88526. var indices = this._source.getIndices();
  88527. if (!indices || !positions) {
  88528. return;
  88529. }
  88530. // First let's find adjacencies
  88531. var adjacencies = new Array();
  88532. var faceNormals = new Array();
  88533. var index;
  88534. var faceAdjacencies;
  88535. // Prepare faces
  88536. for (index = 0; index < indices.length; index += 3) {
  88537. faceAdjacencies = new FaceAdjacencies();
  88538. var p0Index = indices[index];
  88539. var p1Index = indices[index + 1];
  88540. var p2Index = indices[index + 2];
  88541. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  88542. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  88543. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  88544. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  88545. faceNormal.normalize();
  88546. faceNormals.push(faceNormal);
  88547. adjacencies.push(faceAdjacencies);
  88548. }
  88549. // Scan
  88550. for (index = 0; index < adjacencies.length; index++) {
  88551. faceAdjacencies = adjacencies[index];
  88552. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  88553. var otherFaceAdjacencies = adjacencies[otherIndex];
  88554. if (faceAdjacencies.edgesConnectedCount === 3) {
  88555. break;
  88556. }
  88557. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  88558. continue;
  88559. }
  88560. var otherP0 = indices[otherIndex * 3];
  88561. var otherP1 = indices[otherIndex * 3 + 1];
  88562. var otherP2 = indices[otherIndex * 3 + 2];
  88563. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  88564. var otherEdgeIndex = 0;
  88565. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  88566. continue;
  88567. }
  88568. switch (edgeIndex) {
  88569. case 0:
  88570. if (this._checkVerticesInsteadOfIndices) {
  88571. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88572. }
  88573. else {
  88574. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  88575. }
  88576. break;
  88577. case 1:
  88578. if (this._checkVerticesInsteadOfIndices) {
  88579. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88580. }
  88581. else {
  88582. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  88583. }
  88584. break;
  88585. case 2:
  88586. if (this._checkVerticesInsteadOfIndices) {
  88587. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88588. }
  88589. else {
  88590. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  88591. }
  88592. break;
  88593. }
  88594. if (otherEdgeIndex === -1) {
  88595. continue;
  88596. }
  88597. faceAdjacencies.edges[edgeIndex] = otherIndex;
  88598. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  88599. faceAdjacencies.edgesConnectedCount++;
  88600. otherFaceAdjacencies.edgesConnectedCount++;
  88601. if (faceAdjacencies.edgesConnectedCount === 3) {
  88602. break;
  88603. }
  88604. }
  88605. }
  88606. }
  88607. // Create lines
  88608. for (index = 0; index < adjacencies.length; index++) {
  88609. // 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
  88610. var current = adjacencies[index];
  88611. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  88612. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  88613. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  88614. }
  88615. // Merge into a single mesh
  88616. var engine = this._source.getScene().getEngine();
  88617. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  88618. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  88619. this._ib = engine.createIndexBuffer(this._linesIndices);
  88620. this._indicesCount = this._linesIndices.length;
  88621. };
  88622. EdgesRenderer.prototype.render = function () {
  88623. var scene = this._source.getScene();
  88624. if (!this._lineShader.isReady() || !scene.activeCamera) {
  88625. return;
  88626. }
  88627. var engine = scene.getEngine();
  88628. this._lineShader._preBind();
  88629. // VBOs
  88630. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  88631. scene.resetCachedMaterial();
  88632. this._lineShader.setColor4("color", this._source.edgesColor);
  88633. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  88634. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  88635. }
  88636. else {
  88637. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  88638. }
  88639. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  88640. this._lineShader.bind(this._source.getWorldMatrix());
  88641. // Draw order
  88642. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  88643. this._lineShader.unbind();
  88644. engine.setDepthWrite(true);
  88645. };
  88646. return EdgesRenderer;
  88647. }());
  88648. BABYLON.EdgesRenderer = EdgesRenderer;
  88649. })(BABYLON || (BABYLON = {}));
  88650. //# sourceMappingURL=babylon.edgesRenderer.js.map
  88651. "use strict";
  88652. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88653. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88654. s = arguments[i];
  88655. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88656. t[p] = s[p];
  88657. }
  88658. return t;
  88659. };
  88660. var BABYLON;
  88661. (function (BABYLON) {
  88662. /**
  88663. * The effect layer Helps adding post process effect blended with the main pass.
  88664. *
  88665. * This can be for instance use to generate glow or higlight effects on the scene.
  88666. *
  88667. * The effect layer class can not be used directly and is intented to inherited from to be
  88668. * customized per effects.
  88669. */
  88670. var EffectLayer = /** @class */ (function () {
  88671. /**
  88672. * Instantiates a new effect Layer and references it in the scene.
  88673. * @param name The name of the layer
  88674. * @param scene The scene to use the layer in
  88675. */
  88676. function EffectLayer(
  88677. /** The Friendly of the effect in the scene */
  88678. name, scene) {
  88679. this._vertexBuffers = {};
  88680. this._maxSize = 0;
  88681. this._mainTextureDesiredSize = { width: 0, height: 0 };
  88682. this._shouldRender = true;
  88683. this._postProcesses = [];
  88684. this._textures = [];
  88685. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  88686. /**
  88687. * The clear color of the texture used to generate the glow map.
  88688. */
  88689. this.neutralColor = new BABYLON.Color4();
  88690. /**
  88691. * Specifies wether the highlight layer is enabled or not.
  88692. */
  88693. this.isEnabled = true;
  88694. /**
  88695. * An event triggered when the effect layer has been disposed.
  88696. */
  88697. this.onDisposeObservable = new BABYLON.Observable();
  88698. /**
  88699. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  88700. */
  88701. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  88702. /**
  88703. * An event triggered when the generated texture is being merged in the scene.
  88704. */
  88705. this.onBeforeComposeObservable = new BABYLON.Observable();
  88706. /**
  88707. * An event triggered when the generated texture has been merged in the scene.
  88708. */
  88709. this.onAfterComposeObservable = new BABYLON.Observable();
  88710. /**
  88711. * An event triggered when the efffect layer changes its size.
  88712. */
  88713. this.onSizeChangedObservable = new BABYLON.Observable();
  88714. this.name = name;
  88715. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88716. this._engine = scene.getEngine();
  88717. this._maxSize = this._engine.getCaps().maxTextureSize;
  88718. this._scene.effectLayers.push(this);
  88719. // Generate Buffers
  88720. this._generateIndexBuffer();
  88721. this._genrateVertexBuffer();
  88722. }
  88723. Object.defineProperty(EffectLayer.prototype, "camera", {
  88724. /**
  88725. * Gets the camera attached to the layer.
  88726. */
  88727. get: function () {
  88728. return this._effectLayerOptions.camera;
  88729. },
  88730. enumerable: true,
  88731. configurable: true
  88732. });
  88733. /**
  88734. * Initializes the effect layer with the required options.
  88735. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  88736. */
  88737. EffectLayer.prototype._init = function (options) {
  88738. // Adapt options
  88739. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  88740. this._setMainTextureSize();
  88741. this._createMainTexture();
  88742. this._createTextureAndPostProcesses();
  88743. this._mergeEffect = this._createMergeEffect();
  88744. };
  88745. /**
  88746. * Generates the index buffer of the full screen quad blending to the main canvas.
  88747. */
  88748. EffectLayer.prototype._generateIndexBuffer = function () {
  88749. // Indices
  88750. var indices = [];
  88751. indices.push(0);
  88752. indices.push(1);
  88753. indices.push(2);
  88754. indices.push(0);
  88755. indices.push(2);
  88756. indices.push(3);
  88757. this._indexBuffer = this._engine.createIndexBuffer(indices);
  88758. };
  88759. /**
  88760. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  88761. */
  88762. EffectLayer.prototype._genrateVertexBuffer = function () {
  88763. // VBO
  88764. var vertices = [];
  88765. vertices.push(1, 1);
  88766. vertices.push(-1, 1);
  88767. vertices.push(-1, -1);
  88768. vertices.push(1, -1);
  88769. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88771. };
  88772. /**
  88773. * Sets the main texture desired size which is the closest power of two
  88774. * of the engine canvas size.
  88775. */
  88776. EffectLayer.prototype._setMainTextureSize = function () {
  88777. if (this._effectLayerOptions.mainTextureFixedSize) {
  88778. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  88779. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  88780. }
  88781. else {
  88782. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  88783. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  88784. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  88785. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  88786. }
  88787. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  88788. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  88789. };
  88790. /**
  88791. * Creates the main texture for the effect layer.
  88792. */
  88793. EffectLayer.prototype._createMainTexture = function () {
  88794. var _this = this;
  88795. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  88796. width: this._mainTextureDesiredSize.width,
  88797. height: this._mainTextureDesiredSize.height
  88798. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88799. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  88800. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88801. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88802. this._mainTexture.anisotropicFilteringLevel = 1;
  88803. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88804. this._mainTexture.renderParticles = false;
  88805. this._mainTexture.renderList = null;
  88806. this._mainTexture.ignoreCameraViewport = true;
  88807. // Custom render function
  88808. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88809. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  88810. var index;
  88811. var engine = _this._scene.getEngine();
  88812. if (depthOnlySubMeshes.length) {
  88813. engine.setColorWrite(false);
  88814. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88815. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  88816. }
  88817. engine.setColorWrite(true);
  88818. }
  88819. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88820. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  88821. }
  88822. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88823. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  88824. }
  88825. for (index = 0; index < transparentSubMeshes.length; index++) {
  88826. _this._renderSubMesh(transparentSubMeshes.data[index]);
  88827. }
  88828. };
  88829. this._mainTexture.onClearObservable.add(function (engine) {
  88830. engine.clear(_this.neutralColor, true, true, true);
  88831. });
  88832. };
  88833. /**
  88834. * Checks for the readiness of the element composing the layer.
  88835. * @param subMesh the mesh to check for
  88836. * @param useInstances specify wether or not to use instances to render the mesh
  88837. * @param emissiveTexture the associated emissive texture used to generate the glow
  88838. * @return true if ready otherwise, false
  88839. */
  88840. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  88841. var material = subMesh.getMaterial();
  88842. if (!material) {
  88843. return false;
  88844. }
  88845. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  88846. return false;
  88847. }
  88848. var defines = [];
  88849. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88850. var mesh = subMesh.getMesh();
  88851. var uv1 = false;
  88852. var uv2 = false;
  88853. // Alpha test
  88854. if (material && material.needAlphaTesting()) {
  88855. var alphaTexture = material.getAlphaTestTexture();
  88856. if (alphaTexture) {
  88857. defines.push("#define ALPHATEST");
  88858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  88859. alphaTexture.coordinatesIndex === 1) {
  88860. defines.push("#define DIFFUSEUV2");
  88861. uv2 = true;
  88862. }
  88863. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88864. defines.push("#define DIFFUSEUV1");
  88865. uv1 = true;
  88866. }
  88867. }
  88868. }
  88869. // Emissive
  88870. if (emissiveTexture) {
  88871. defines.push("#define EMISSIVE");
  88872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  88873. emissiveTexture.coordinatesIndex === 1) {
  88874. defines.push("#define EMISSIVEUV2");
  88875. uv2 = true;
  88876. }
  88877. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88878. defines.push("#define EMISSIVEUV1");
  88879. uv1 = true;
  88880. }
  88881. }
  88882. if (uv1) {
  88883. attribs.push(BABYLON.VertexBuffer.UVKind);
  88884. defines.push("#define UV1");
  88885. }
  88886. if (uv2) {
  88887. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88888. defines.push("#define UV2");
  88889. }
  88890. // Bones
  88891. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88894. if (mesh.numBoneInfluencers > 4) {
  88895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88897. }
  88898. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88899. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88900. }
  88901. else {
  88902. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88903. }
  88904. // Morph targets
  88905. var manager = mesh.morphTargetManager;
  88906. var morphInfluencers = 0;
  88907. if (manager) {
  88908. if (manager.numInfluencers > 0) {
  88909. defines.push("#define MORPHTARGETS");
  88910. morphInfluencers = manager.numInfluencers;
  88911. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  88912. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  88913. }
  88914. }
  88915. // Instances
  88916. if (useInstances) {
  88917. defines.push("#define INSTANCES");
  88918. attribs.push("world0");
  88919. attribs.push("world1");
  88920. attribs.push("world2");
  88921. attribs.push("world3");
  88922. }
  88923. // Get correct effect
  88924. var join = defines.join("\n");
  88925. if (this._cachedDefines !== join) {
  88926. this._cachedDefines = join;
  88927. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  88928. }
  88929. return this._effectLayerMapGenerationEffect.isReady();
  88930. };
  88931. /**
  88932. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  88933. */
  88934. EffectLayer.prototype.render = function () {
  88935. var currentEffect = this._mergeEffect;
  88936. // Check
  88937. if (!currentEffect.isReady())
  88938. return;
  88939. for (var i = 0; i < this._postProcesses.length; i++) {
  88940. if (!this._postProcesses[i].isReady()) {
  88941. return;
  88942. }
  88943. }
  88944. var engine = this._scene.getEngine();
  88945. this.onBeforeComposeObservable.notifyObservers(this);
  88946. // Render
  88947. engine.enableEffect(currentEffect);
  88948. engine.setState(false);
  88949. // VBOs
  88950. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88951. // Cache
  88952. var previousAlphaMode = engine.getAlphaMode();
  88953. // Go Blend.
  88954. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  88955. // Blends the map on the main canvas.
  88956. this._internalRender(currentEffect);
  88957. // Restore Alpha
  88958. engine.setAlphaMode(previousAlphaMode);
  88959. this.onAfterComposeObservable.notifyObservers(this);
  88960. // Handle size changes.
  88961. var size = this._mainTexture.getSize();
  88962. this._setMainTextureSize();
  88963. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  88964. // Recreate RTT and post processes on size change.
  88965. this.onSizeChangedObservable.notifyObservers(this);
  88966. this._disposeTextureAndPostProcesses();
  88967. this._createMainTexture();
  88968. this._createTextureAndPostProcesses();
  88969. }
  88970. };
  88971. /**
  88972. * Determine if a given mesh will be used in the current effect.
  88973. * @param mesh mesh to test
  88974. * @returns true if the mesh will be used
  88975. */
  88976. EffectLayer.prototype.hasMesh = function (mesh) {
  88977. return true;
  88978. };
  88979. /**
  88980. * Returns true if the layer contains information to display, otherwise false.
  88981. * @returns true if the glow layer should be rendered
  88982. */
  88983. EffectLayer.prototype.shouldRender = function () {
  88984. return this.isEnabled && this._shouldRender;
  88985. };
  88986. /**
  88987. * Returns true if the mesh should render, otherwise false.
  88988. * @param mesh The mesh to render
  88989. * @returns true if it should render otherwise false
  88990. */
  88991. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  88992. return true;
  88993. };
  88994. /**
  88995. * Returns true if the mesh should render, otherwise false.
  88996. * @param mesh The mesh to render
  88997. * @returns true if it should render otherwise false
  88998. */
  88999. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  89000. return true;
  89001. };
  89002. /**
  89003. * Renders the submesh passed in parameter to the generation map.
  89004. */
  89005. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  89006. var _this = this;
  89007. if (!this.shouldRender()) {
  89008. return;
  89009. }
  89010. var material = subMesh.getMaterial();
  89011. var mesh = subMesh.getRenderingMesh();
  89012. var scene = this._scene;
  89013. var engine = scene.getEngine();
  89014. if (!material) {
  89015. return;
  89016. }
  89017. // Do not block in blend mode.
  89018. if (material.needAlphaBlendingForMesh(mesh)) {
  89019. return;
  89020. }
  89021. // Culling
  89022. engine.setState(material.backFaceCulling);
  89023. // Managing instances
  89024. var batch = mesh._getInstancesRenderList(subMesh._id);
  89025. if (batch.mustReturn) {
  89026. return;
  89027. }
  89028. // Early Exit per mesh
  89029. if (!this._shouldRenderMesh(mesh)) {
  89030. return;
  89031. }
  89032. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89033. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  89034. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  89035. engine.enableEffect(this._effectLayerMapGenerationEffect);
  89036. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  89037. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  89038. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  89039. // Alpha test
  89040. if (material && material.needAlphaTesting()) {
  89041. var alphaTexture = material.getAlphaTestTexture();
  89042. if (alphaTexture) {
  89043. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  89044. var textureMatrix = alphaTexture.getTextureMatrix();
  89045. if (textureMatrix) {
  89046. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  89047. }
  89048. }
  89049. }
  89050. // Glow emissive only
  89051. if (this._emissiveTextureAndColor.texture) {
  89052. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  89053. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  89054. }
  89055. // Bones
  89056. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89057. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89058. }
  89059. // Morph targets
  89060. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  89061. // Draw
  89062. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  89063. }
  89064. else {
  89065. // Need to reset refresh rate of the shadowMap
  89066. this._mainTexture.resetRefreshCounter();
  89067. }
  89068. };
  89069. /**
  89070. * Rebuild the required buffers.
  89071. * @ignore Internal use only.
  89072. */
  89073. EffectLayer.prototype._rebuild = function () {
  89074. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89075. if (vb) {
  89076. vb._rebuild();
  89077. }
  89078. this._generateIndexBuffer();
  89079. };
  89080. /**
  89081. * Dispose only the render target textures and post process.
  89082. */
  89083. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  89084. this._mainTexture.dispose();
  89085. for (var i = 0; i < this._postProcesses.length; i++) {
  89086. if (this._postProcesses[i]) {
  89087. this._postProcesses[i].dispose();
  89088. }
  89089. }
  89090. this._postProcesses = [];
  89091. for (var i = 0; i < this._textures.length; i++) {
  89092. if (this._textures[i]) {
  89093. this._textures[i].dispose();
  89094. }
  89095. }
  89096. this._textures = [];
  89097. };
  89098. /**
  89099. * Dispose the highlight layer and free resources.
  89100. */
  89101. EffectLayer.prototype.dispose = function () {
  89102. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89103. if (vertexBuffer) {
  89104. vertexBuffer.dispose();
  89105. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89106. }
  89107. if (this._indexBuffer) {
  89108. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89109. this._indexBuffer = null;
  89110. }
  89111. // Clean textures and post processes
  89112. this._disposeTextureAndPostProcesses();
  89113. // Remove from scene
  89114. var index = this._scene.effectLayers.indexOf(this, 0);
  89115. if (index > -1) {
  89116. this._scene.effectLayers.splice(index, 1);
  89117. }
  89118. // Callback
  89119. this.onDisposeObservable.notifyObservers(this);
  89120. this.onDisposeObservable.clear();
  89121. this.onBeforeRenderMainTextureObservable.clear();
  89122. this.onBeforeComposeObservable.clear();
  89123. this.onAfterComposeObservable.clear();
  89124. this.onSizeChangedObservable.clear();
  89125. };
  89126. /**
  89127. * Gets the class name of the effect layer
  89128. * @returns the string with the class name of the effect layer
  89129. */
  89130. EffectLayer.prototype.getClassName = function () {
  89131. return "EffectLayer";
  89132. };
  89133. __decorate([
  89134. BABYLON.serialize()
  89135. ], EffectLayer.prototype, "name", void 0);
  89136. __decorate([
  89137. BABYLON.serializeAsColor4()
  89138. ], EffectLayer.prototype, "neutralColor", void 0);
  89139. __decorate([
  89140. BABYLON.serialize()
  89141. ], EffectLayer.prototype, "isEnabled", void 0);
  89142. __decorate([
  89143. BABYLON.serializeAsCameraReference()
  89144. ], EffectLayer.prototype, "camera", null);
  89145. return EffectLayer;
  89146. }());
  89147. BABYLON.EffectLayer = EffectLayer;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.effectLayer.js.map
  89150. "use strict";
  89151. var BABYLON;
  89152. (function (BABYLON) {
  89153. /**
  89154. * Special Glow Blur post process only blurring the alpha channel
  89155. * It enforces keeping the most luminous color in the color channel.
  89156. */
  89157. var GlowBlurPostProcess = /** @class */ (function (_super) {
  89158. __extends(GlowBlurPostProcess, _super);
  89159. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  89160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89161. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  89162. _this.direction = direction;
  89163. _this.kernel = kernel;
  89164. _this.onApplyObservable.add(function (effect) {
  89165. effect.setFloat2("screenSize", _this.width, _this.height);
  89166. effect.setVector2("direction", _this.direction);
  89167. effect.setFloat("blurWidth", _this.kernel);
  89168. });
  89169. return _this;
  89170. }
  89171. return GlowBlurPostProcess;
  89172. }(BABYLON.PostProcess));
  89173. /**
  89174. * The highlight layer Helps adding a glow effect around a mesh.
  89175. *
  89176. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89177. * glowy meshes to your scene.
  89178. *
  89179. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  89180. */
  89181. var HighlightLayer = /** @class */ (function (_super) {
  89182. __extends(HighlightLayer, _super);
  89183. /**
  89184. * Instantiates a new highlight Layer and references it to the scene..
  89185. * @param name The name of the layer
  89186. * @param scene The scene to use the layer in
  89187. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  89188. */
  89189. function HighlightLayer(name, scene, options) {
  89190. var _this = _super.call(this, name, scene) || this;
  89191. _this.name = name;
  89192. /**
  89193. * Specifies whether or not the inner glow is ACTIVE in the layer.
  89194. */
  89195. _this.innerGlow = true;
  89196. /**
  89197. * Specifies whether or not the outer glow is ACTIVE in the layer.
  89198. */
  89199. _this.outerGlow = true;
  89200. /**
  89201. * An event triggered when the highlight layer is being blurred.
  89202. */
  89203. _this.onBeforeBlurObservable = new BABYLON.Observable();
  89204. /**
  89205. * An event triggered when the highlight layer has been blurred.
  89206. */
  89207. _this.onAfterBlurObservable = new BABYLON.Observable();
  89208. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  89209. _this._meshes = {};
  89210. _this._excludedMeshes = {};
  89211. _this.neutralColor = HighlightLayer.NeutralColor;
  89212. // Warn on stencil
  89213. if (!_this._engine.isStencilEnable) {
  89214. 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 }");
  89215. }
  89216. // Adapt options
  89217. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89218. // Initialize the layer
  89219. _this._init({
  89220. alphaBlendingMode: _this._options.alphaBlendingMode,
  89221. camera: _this._options.camera,
  89222. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89223. mainTextureRatio: _this._options.mainTextureRatio
  89224. });
  89225. // Do not render as long as no meshes have been added
  89226. _this._shouldRender = false;
  89227. return _this;
  89228. }
  89229. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  89230. /**
  89231. * Gets the horizontal size of the blur.
  89232. */
  89233. get: function () {
  89234. return this._horizontalBlurPostprocess.kernel;
  89235. },
  89236. /**
  89237. * Specifies the horizontal size of the blur.
  89238. */
  89239. set: function (value) {
  89240. this._horizontalBlurPostprocess.kernel = value;
  89241. },
  89242. enumerable: true,
  89243. configurable: true
  89244. });
  89245. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  89246. /**
  89247. * Gets the vertical size of the blur.
  89248. */
  89249. get: function () {
  89250. return this._verticalBlurPostprocess.kernel;
  89251. },
  89252. /**
  89253. * Specifies the vertical size of the blur.
  89254. */
  89255. set: function (value) {
  89256. this._verticalBlurPostprocess.kernel = value;
  89257. },
  89258. enumerable: true,
  89259. configurable: true
  89260. });
  89261. /**
  89262. * Get the effect name of the layer.
  89263. * @return The effect name
  89264. */
  89265. HighlightLayer.prototype.getEffectName = function () {
  89266. return HighlightLayer.EffectName;
  89267. };
  89268. /**
  89269. * Create the merge effect. This is the shader use to blit the information back
  89270. * to the main canvas at the end of the scene rendering.
  89271. */
  89272. HighlightLayer.prototype._createMergeEffect = function () {
  89273. // Effect
  89274. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  89275. };
  89276. /**
  89277. * Creates the render target textures and post processes used in the highlight layer.
  89278. */
  89279. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  89280. var _this = this;
  89281. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  89282. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  89283. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89284. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89285. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  89286. width: blurTextureWidth,
  89287. height: blurTextureHeight
  89288. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89289. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89290. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89291. this._blurTexture.anisotropicFilteringLevel = 16;
  89292. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89293. this._blurTexture.renderParticles = false;
  89294. this._blurTexture.ignoreCameraViewport = true;
  89295. this._textures = [this._blurTexture];
  89296. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  89297. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89298. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  89299. effect.setTexture("textureSampler", _this._mainTexture);
  89300. });
  89301. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89302. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89303. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89304. });
  89305. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89306. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  89307. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89308. });
  89309. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89310. }
  89311. else {
  89312. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  89313. width: blurTextureWidth,
  89314. height: blurTextureHeight
  89315. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89316. this._horizontalBlurPostprocess.width = blurTextureWidth;
  89317. this._horizontalBlurPostprocess.height = blurTextureHeight;
  89318. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89319. effect.setTexture("textureSampler", _this._mainTexture);
  89320. });
  89321. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  89322. width: blurTextureWidth,
  89323. height: blurTextureHeight
  89324. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89325. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89326. }
  89327. this._mainTexture.onAfterUnbindObservable.add(function () {
  89328. _this.onBeforeBlurObservable.notifyObservers(_this);
  89329. var internalTexture = _this._blurTexture.getInternalTexture();
  89330. if (internalTexture) {
  89331. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  89332. }
  89333. _this.onAfterBlurObservable.notifyObservers(_this);
  89334. });
  89335. // Prevent autoClear.
  89336. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89337. };
  89338. /**
  89339. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89340. */
  89341. HighlightLayer.prototype.needStencil = function () {
  89342. return true;
  89343. };
  89344. /**
  89345. * Checks for the readiness of the element composing the layer.
  89346. * @param subMesh the mesh to check for
  89347. * @param useInstances specify wether or not to use instances to render the mesh
  89348. * @param emissiveTexture the associated emissive texture used to generate the glow
  89349. * @return true if ready otherwise, false
  89350. */
  89351. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  89352. var material = subMesh.getMaterial();
  89353. var mesh = subMesh.getRenderingMesh();
  89354. if (!material || !mesh || !this._meshes) {
  89355. return false;
  89356. }
  89357. var emissiveTexture = null;
  89358. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89359. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89360. emissiveTexture = material.emissiveTexture;
  89361. }
  89362. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89363. };
  89364. /**
  89365. * Implementation specific of rendering the generating effect on the main canvas.
  89366. * @param effect The effect used to render through
  89367. */
  89368. HighlightLayer.prototype._internalRender = function (effect) {
  89369. // Texture
  89370. effect.setTexture("textureSampler", this._blurTexture);
  89371. // Cache
  89372. var engine = this._engine;
  89373. var previousStencilBuffer = engine.getStencilBuffer();
  89374. var previousStencilFunction = engine.getStencilFunction();
  89375. var previousStencilMask = engine.getStencilMask();
  89376. var previousStencilOperationPass = engine.getStencilOperationPass();
  89377. var previousStencilOperationFail = engine.getStencilOperationFail();
  89378. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  89379. var previousStencilReference = engine.getStencilFunctionReference();
  89380. // Stencil operations
  89381. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  89382. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  89383. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  89384. // Draw order
  89385. engine.setStencilMask(0x00);
  89386. engine.setStencilBuffer(true);
  89387. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  89388. // 2 passes inner outer
  89389. if (this.outerGlow) {
  89390. effect.setFloat("offset", 0);
  89391. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  89392. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89393. }
  89394. if (this.innerGlow) {
  89395. effect.setFloat("offset", 1);
  89396. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  89397. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89398. }
  89399. // Restore Cache
  89400. engine.setStencilFunction(previousStencilFunction);
  89401. engine.setStencilMask(previousStencilMask);
  89402. engine.setStencilBuffer(previousStencilBuffer);
  89403. engine.setStencilOperationPass(previousStencilOperationPass);
  89404. engine.setStencilOperationFail(previousStencilOperationFail);
  89405. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  89406. engine.setStencilFunctionReference(previousStencilReference);
  89407. };
  89408. /**
  89409. * Returns true if the layer contains information to display, otherwise false.
  89410. */
  89411. HighlightLayer.prototype.shouldRender = function () {
  89412. if (_super.prototype.shouldRender.call(this)) {
  89413. return this._meshes ? true : false;
  89414. }
  89415. return false;
  89416. };
  89417. /**
  89418. * Returns true if the mesh should render, otherwise false.
  89419. * @param mesh The mesh to render
  89420. * @returns true if it should render otherwise false
  89421. */
  89422. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  89423. // Excluded Mesh
  89424. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  89425. return false;
  89426. }
  89427. ;
  89428. return true;
  89429. };
  89430. /**
  89431. * Sets the required values for both the emissive texture and and the main color.
  89432. */
  89433. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89434. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89435. if (highlightLayerMesh) {
  89436. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  89437. }
  89438. else {
  89439. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89440. }
  89441. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89442. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89443. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  89444. }
  89445. else {
  89446. this._emissiveTextureAndColor.texture = null;
  89447. }
  89448. };
  89449. /**
  89450. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  89451. * @param mesh The mesh to exclude from the highlight layer
  89452. */
  89453. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  89454. if (!this._excludedMeshes) {
  89455. return;
  89456. }
  89457. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89458. if (!meshExcluded) {
  89459. this._excludedMeshes[mesh.uniqueId] = {
  89460. mesh: mesh,
  89461. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  89462. mesh.getEngine().setStencilBuffer(false);
  89463. }),
  89464. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  89465. mesh.getEngine().setStencilBuffer(true);
  89466. }),
  89467. };
  89468. }
  89469. };
  89470. /**
  89471. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  89472. * @param mesh The mesh to highlight
  89473. */
  89474. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  89475. if (!this._excludedMeshes) {
  89476. return;
  89477. }
  89478. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89479. if (meshExcluded) {
  89480. if (meshExcluded.beforeRender) {
  89481. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  89482. }
  89483. if (meshExcluded.afterRender) {
  89484. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  89485. }
  89486. }
  89487. this._excludedMeshes[mesh.uniqueId] = null;
  89488. };
  89489. /**
  89490. * Determine if a given mesh will be highlighted by the current HighlightLayer
  89491. * @param mesh mesh to test
  89492. * @returns true if the mesh will be highlighted by the current HighlightLayer
  89493. */
  89494. HighlightLayer.prototype.hasMesh = function (mesh) {
  89495. if (!this._meshes) {
  89496. return false;
  89497. }
  89498. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  89499. };
  89500. /**
  89501. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  89502. * @param mesh The mesh to highlight
  89503. * @param color The color of the highlight
  89504. * @param glowEmissiveOnly Extract the glow from the emissive texture
  89505. */
  89506. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  89507. var _this = this;
  89508. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  89509. if (!this._meshes) {
  89510. return;
  89511. }
  89512. var meshHighlight = this._meshes[mesh.uniqueId];
  89513. if (meshHighlight) {
  89514. meshHighlight.color = color;
  89515. }
  89516. else {
  89517. this._meshes[mesh.uniqueId] = {
  89518. mesh: mesh,
  89519. color: color,
  89520. // Lambda required for capture due to Observable this context
  89521. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  89522. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  89523. _this._defaultStencilReference(mesh);
  89524. }
  89525. else {
  89526. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  89527. }
  89528. }),
  89529. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  89530. glowEmissiveOnly: glowEmissiveOnly
  89531. };
  89532. }
  89533. this._shouldRender = true;
  89534. };
  89535. /**
  89536. * Remove a mesh from the highlight layer in order to make it stop glowing.
  89537. * @param mesh The mesh to highlight
  89538. */
  89539. HighlightLayer.prototype.removeMesh = function (mesh) {
  89540. if (!this._meshes) {
  89541. return;
  89542. }
  89543. var meshHighlight = this._meshes[mesh.uniqueId];
  89544. if (meshHighlight) {
  89545. if (meshHighlight.observerHighlight) {
  89546. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89547. }
  89548. if (meshHighlight.observerDefault) {
  89549. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89550. }
  89551. delete this._meshes[mesh.uniqueId];
  89552. }
  89553. this._shouldRender = false;
  89554. for (var meshHighlightToCheck in this._meshes) {
  89555. if (this._meshes[meshHighlightToCheck]) {
  89556. this._shouldRender = true;
  89557. break;
  89558. }
  89559. }
  89560. };
  89561. /**
  89562. * Force the stencil to the normal expected value for none glowing parts
  89563. */
  89564. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  89565. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  89566. };
  89567. /**
  89568. * Free any resources and references associated to a mesh.
  89569. * Internal use
  89570. * @param mesh The mesh to free.
  89571. */
  89572. HighlightLayer.prototype._disposeMesh = function (mesh) {
  89573. this.removeMesh(mesh);
  89574. this.removeExcludedMesh(mesh);
  89575. };
  89576. /**
  89577. * Dispose the highlight layer and free resources.
  89578. */
  89579. HighlightLayer.prototype.dispose = function () {
  89580. if (this._meshes) {
  89581. // Clean mesh references
  89582. for (var id in this._meshes) {
  89583. var meshHighlight = this._meshes[id];
  89584. if (meshHighlight && meshHighlight.mesh) {
  89585. if (meshHighlight.observerHighlight) {
  89586. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89587. }
  89588. if (meshHighlight.observerDefault) {
  89589. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89590. }
  89591. }
  89592. }
  89593. this._meshes = null;
  89594. }
  89595. if (this._excludedMeshes) {
  89596. for (var id in this._excludedMeshes) {
  89597. var meshHighlight = this._excludedMeshes[id];
  89598. if (meshHighlight) {
  89599. if (meshHighlight.beforeRender) {
  89600. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  89601. }
  89602. if (meshHighlight.afterRender) {
  89603. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  89604. }
  89605. }
  89606. }
  89607. this._excludedMeshes = null;
  89608. }
  89609. _super.prototype.dispose.call(this);
  89610. };
  89611. /**
  89612. * Effect Name of the highlight layer.
  89613. */
  89614. HighlightLayer.EffectName = "HighlightLayer";
  89615. /**
  89616. * The neutral color used during the preparation of the glow effect.
  89617. * This is black by default as the blend operation is a blend operation.
  89618. */
  89619. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  89620. /**
  89621. * Stencil value used for glowing meshes.
  89622. */
  89623. HighlightLayer.GlowingMeshStencilReference = 0x02;
  89624. /**
  89625. * Stencil value used for the other meshes in the scene.
  89626. */
  89627. HighlightLayer.NormalMeshStencilReference = 0x01;
  89628. return HighlightLayer;
  89629. }(BABYLON.EffectLayer));
  89630. BABYLON.HighlightLayer = HighlightLayer;
  89631. })(BABYLON || (BABYLON = {}));
  89632. //# sourceMappingURL=babylon.highlightLayer.js.map
  89633. "use strict";
  89634. var BABYLON;
  89635. (function (BABYLON) {
  89636. /**
  89637. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  89638. *
  89639. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89640. * glowy meshes to your scene.
  89641. *
  89642. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  89643. */
  89644. var GlowLayer = /** @class */ (function (_super) {
  89645. __extends(GlowLayer, _super);
  89646. /**
  89647. * Instantiates a new glow Layer and references it to the scene.
  89648. * @param name The name of the layer
  89649. * @param scene The scene to use the layer in
  89650. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  89651. */
  89652. function GlowLayer(name, scene, options) {
  89653. var _this = _super.call(this, name, scene) || this;
  89654. _this._intensity = 1.0;
  89655. _this._includedOnlyMeshes = [];
  89656. _this._excludedMeshes = [];
  89657. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  89658. // Adapt options
  89659. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  89660. // Initialize the layer
  89661. _this._init({
  89662. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  89663. camera: _this._options.camera,
  89664. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89665. mainTextureRatio: _this._options.mainTextureRatio
  89666. });
  89667. return _this;
  89668. }
  89669. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  89670. /**
  89671. * Gets the kernel size of the blur.
  89672. */
  89673. get: function () {
  89674. return this._horizontalBlurPostprocess1.kernel;
  89675. },
  89676. /**
  89677. * Sets the kernel size of the blur.
  89678. */
  89679. set: function (value) {
  89680. this._horizontalBlurPostprocess1.kernel = value;
  89681. this._verticalBlurPostprocess1.kernel = value;
  89682. this._horizontalBlurPostprocess2.kernel = value;
  89683. this._verticalBlurPostprocess2.kernel = value;
  89684. },
  89685. enumerable: true,
  89686. configurable: true
  89687. });
  89688. Object.defineProperty(GlowLayer.prototype, "intensity", {
  89689. /**
  89690. * Gets the glow intensity.
  89691. */
  89692. get: function () {
  89693. return this._intensity;
  89694. },
  89695. /**
  89696. * Sets the glow intensity.
  89697. */
  89698. set: function (value) {
  89699. this._intensity = value;
  89700. },
  89701. enumerable: true,
  89702. configurable: true
  89703. });
  89704. /**
  89705. * Get the effect name of the layer.
  89706. * @return The effect name
  89707. */
  89708. GlowLayer.prototype.getEffectName = function () {
  89709. return GlowLayer.EffectName;
  89710. };
  89711. /**
  89712. * Create the merge effect. This is the shader use to blit the information back
  89713. * to the main canvas at the end of the scene rendering.
  89714. */
  89715. GlowLayer.prototype._createMergeEffect = function () {
  89716. // Effect
  89717. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  89718. };
  89719. /**
  89720. * Creates the render target textures and post processes used in the glow layer.
  89721. */
  89722. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  89723. var _this = this;
  89724. var blurTextureWidth = this._mainTextureDesiredSize.width;
  89725. var blurTextureHeight = this._mainTextureDesiredSize.height;
  89726. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89727. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89728. var textureType = 0;
  89729. if (this._engine.getCaps().textureHalfFloatRender) {
  89730. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89731. }
  89732. else {
  89733. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89734. }
  89735. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  89736. width: blurTextureWidth,
  89737. height: blurTextureHeight
  89738. }, this._scene, false, true, textureType);
  89739. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89740. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89741. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89742. this._blurTexture1.renderParticles = false;
  89743. this._blurTexture1.ignoreCameraViewport = true;
  89744. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  89745. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  89746. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  89747. width: blurTextureWidth2,
  89748. height: blurTextureHeight2
  89749. }, this._scene, false, true, textureType);
  89750. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89751. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89752. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89753. this._blurTexture2.renderParticles = false;
  89754. this._blurTexture2.ignoreCameraViewport = true;
  89755. this._textures = [this._blurTexture1, this._blurTexture2];
  89756. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  89757. width: blurTextureWidth,
  89758. height: blurTextureHeight
  89759. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89760. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  89761. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  89762. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  89763. effect.setTexture("textureSampler", _this._mainTexture);
  89764. });
  89765. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  89766. width: blurTextureWidth,
  89767. height: blurTextureHeight
  89768. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89769. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  89770. width: blurTextureWidth2,
  89771. height: blurTextureHeight2
  89772. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89773. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  89774. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  89775. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  89776. effect.setTexture("textureSampler", _this._blurTexture1);
  89777. });
  89778. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  89779. width: blurTextureWidth2,
  89780. height: blurTextureHeight2
  89781. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89782. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  89783. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  89784. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  89785. this._mainTexture.samples = this._options.mainTextureSamples;
  89786. this._mainTexture.onAfterUnbindObservable.add(function () {
  89787. var internalTexture = _this._blurTexture1.getInternalTexture();
  89788. if (internalTexture) {
  89789. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  89790. internalTexture = _this._blurTexture2.getInternalTexture();
  89791. if (internalTexture) {
  89792. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  89793. }
  89794. }
  89795. });
  89796. // Prevent autoClear.
  89797. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89798. };
  89799. /**
  89800. * Checks for the readiness of the element composing the layer.
  89801. * @param subMesh the mesh to check for
  89802. * @param useInstances specify wether or not to use instances to render the mesh
  89803. * @param emissiveTexture the associated emissive texture used to generate the glow
  89804. * @return true if ready otherwise, false
  89805. */
  89806. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  89807. var material = subMesh.getMaterial();
  89808. var mesh = subMesh.getRenderingMesh();
  89809. if (!material || !mesh) {
  89810. return false;
  89811. }
  89812. var emissiveTexture = material.emissiveTexture;
  89813. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89814. };
  89815. /**
  89816. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89817. */
  89818. GlowLayer.prototype.needStencil = function () {
  89819. return false;
  89820. };
  89821. /**
  89822. * Implementation specific of rendering the generating effect on the main canvas.
  89823. * @param effect The effect used to render through
  89824. */
  89825. GlowLayer.prototype._internalRender = function (effect) {
  89826. // Texture
  89827. effect.setTexture("textureSampler", this._blurTexture1);
  89828. effect.setTexture("textureSampler2", this._blurTexture2);
  89829. effect.setFloat("offset", this._intensity);
  89830. // Cache
  89831. var engine = this._engine;
  89832. var previousStencilBuffer = engine.getStencilBuffer();
  89833. // Draw order
  89834. engine.setStencilBuffer(false);
  89835. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89836. // Draw order
  89837. engine.setStencilBuffer(previousStencilBuffer);
  89838. };
  89839. /**
  89840. * Sets the required values for both the emissive texture and and the main color.
  89841. */
  89842. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89843. var textureLevel = 1.0;
  89844. if (this.customEmissiveTextureSelector) {
  89845. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  89846. }
  89847. else {
  89848. if (material) {
  89849. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89850. if (this._emissiveTextureAndColor.texture) {
  89851. textureLevel = this._emissiveTextureAndColor.texture.level;
  89852. }
  89853. }
  89854. else {
  89855. this._emissiveTextureAndColor.texture = null;
  89856. }
  89857. }
  89858. if (this.customEmissiveColorSelector) {
  89859. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  89860. }
  89861. else {
  89862. if (material.emissiveColor) {
  89863. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  89864. }
  89865. else {
  89866. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89867. }
  89868. }
  89869. };
  89870. /**
  89871. * Returns true if the mesh should render, otherwise false.
  89872. * @param mesh The mesh to render
  89873. * @returns true if it should render otherwise false
  89874. */
  89875. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  89876. return this.hasMesh(mesh);
  89877. };
  89878. /**
  89879. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  89880. * @param mesh The mesh to exclude from the glow layer
  89881. */
  89882. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  89883. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  89884. this._excludedMeshes.push(mesh.uniqueId);
  89885. }
  89886. };
  89887. /**
  89888. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  89889. * @param mesh The mesh to remove
  89890. */
  89891. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  89892. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  89893. if (index !== -1) {
  89894. this._excludedMeshes.splice(index, 1);
  89895. }
  89896. };
  89897. /**
  89898. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  89899. * @param mesh The mesh to include in the glow layer
  89900. */
  89901. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  89902. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  89903. this._includedOnlyMeshes.push(mesh.uniqueId);
  89904. }
  89905. };
  89906. /**
  89907. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  89908. * @param mesh The mesh to remove
  89909. */
  89910. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  89911. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  89912. if (index !== -1) {
  89913. this._includedOnlyMeshes.splice(index, 1);
  89914. }
  89915. };
  89916. /**
  89917. * Determine if a given mesh will be used in the glow layer
  89918. * @param mesh The mesh to test
  89919. * @returns true if the mesh will be highlighted by the current glow layer
  89920. */
  89921. GlowLayer.prototype.hasMesh = function (mesh) {
  89922. // Included Mesh
  89923. if (this._includedOnlyMeshes.length) {
  89924. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  89925. }
  89926. ;
  89927. // Excluded Mesh
  89928. if (this._excludedMeshes.length) {
  89929. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  89930. }
  89931. ;
  89932. return true;
  89933. };
  89934. /**
  89935. * Free any resources and references associated to a mesh.
  89936. * Internal use
  89937. * @param mesh The mesh to free.
  89938. */
  89939. GlowLayer.prototype._disposeMesh = function (mesh) {
  89940. this.removeIncludedOnlyMesh(mesh);
  89941. this.removeExcludedMesh(mesh);
  89942. };
  89943. /**
  89944. * Gets the class name of the effect layer
  89945. * @returns the string with the class name of the effect layer
  89946. */
  89947. GlowLayer.prototype.getClassName = function () {
  89948. return "GlowLayer";
  89949. };
  89950. /**
  89951. * Serializes this glow layer
  89952. * @returns a serialized glow layer object
  89953. */
  89954. GlowLayer.prototype.serialize = function () {
  89955. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89956. var index;
  89957. // Included meshes
  89958. serializationObject.includedMeshes = [];
  89959. if (this._includedOnlyMeshes.length) {
  89960. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  89961. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  89962. if (mesh) {
  89963. serializationObject.includedMeshes.push(mesh.id);
  89964. }
  89965. }
  89966. }
  89967. // Excluded meshes
  89968. serializationObject.excludedMeshes = [];
  89969. if (this._excludedMeshes.length) {
  89970. for (index = 0; index < this._excludedMeshes.length; index++) {
  89971. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  89972. if (mesh) {
  89973. serializationObject.excludedMeshes.push(mesh.id);
  89974. }
  89975. }
  89976. }
  89977. return serializationObject;
  89978. };
  89979. /**
  89980. * Creates a Glow Layer from parsed glow layer data
  89981. * @param parsedGlowLayer defines glow layer data
  89982. * @param scene defines the current scene
  89983. * @param rootUrl defines the root URL containing the glow layer information
  89984. * @returns a parsed Glow Layer
  89985. */
  89986. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  89987. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  89988. var index;
  89989. // Excluded meshes
  89990. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  89991. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  89992. if (mesh) {
  89993. gl.addExcludedMesh(mesh);
  89994. }
  89995. }
  89996. // Included meshes
  89997. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  89998. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  89999. if (mesh) {
  90000. gl.addIncludedOnlyMesh(mesh);
  90001. }
  90002. }
  90003. return gl;
  90004. };
  90005. /**
  90006. * Effect Name of the layer.
  90007. */
  90008. GlowLayer.EffectName = "GlowLayer";
  90009. /**
  90010. * The default blur kernel size used for the glow.
  90011. */
  90012. GlowLayer.DefaultBlurKernelSize = 32;
  90013. /**
  90014. * The default texture size ratio used for the glow.
  90015. */
  90016. GlowLayer.DefaultTextureRatio = 0.5;
  90017. __decorate([
  90018. BABYLON.serialize()
  90019. ], GlowLayer.prototype, "blurKernelSize", null);
  90020. __decorate([
  90021. BABYLON.serialize()
  90022. ], GlowLayer.prototype, "intensity", null);
  90023. __decorate([
  90024. BABYLON.serialize('options')
  90025. ], GlowLayer.prototype, "_options", void 0);
  90026. return GlowLayer;
  90027. }(BABYLON.EffectLayer));
  90028. BABYLON.GlowLayer = GlowLayer;
  90029. })(BABYLON || (BABYLON = {}));
  90030. //# sourceMappingURL=babylon.glowLayer.js.map
  90031. "use strict";
  90032. var BABYLON;
  90033. (function (BABYLON) {
  90034. /**
  90035. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  90036. */
  90037. var AssetTaskState;
  90038. (function (AssetTaskState) {
  90039. /**
  90040. * Initialization
  90041. */
  90042. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  90043. /**
  90044. * Running
  90045. */
  90046. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  90047. /**
  90048. * Done
  90049. */
  90050. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  90051. /**
  90052. * Error
  90053. */
  90054. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  90055. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  90056. /**
  90057. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  90058. */
  90059. var AbstractAssetTask = /** @class */ (function () {
  90060. /**
  90061. * Creates a new {BABYLON.AssetsManager}
  90062. * @param name defines the name of the task
  90063. */
  90064. function AbstractAssetTask(
  90065. /**
  90066. * Task name
  90067. */ name) {
  90068. this.name = name;
  90069. this._isCompleted = false;
  90070. this._taskState = AssetTaskState.INIT;
  90071. }
  90072. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  90073. /**
  90074. * Get if the task is completed
  90075. */
  90076. get: function () {
  90077. return this._isCompleted;
  90078. },
  90079. enumerable: true,
  90080. configurable: true
  90081. });
  90082. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  90083. /**
  90084. * Gets the current state of the task
  90085. */
  90086. get: function () {
  90087. return this._taskState;
  90088. },
  90089. enumerable: true,
  90090. configurable: true
  90091. });
  90092. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  90093. /**
  90094. * Gets the current error object (if task is in error)
  90095. */
  90096. get: function () {
  90097. return this._errorObject;
  90098. },
  90099. enumerable: true,
  90100. configurable: true
  90101. });
  90102. /**
  90103. * Internal only
  90104. * @ignore
  90105. */
  90106. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  90107. if (this._errorObject) {
  90108. return;
  90109. }
  90110. this._errorObject = {
  90111. message: message,
  90112. exception: exception
  90113. };
  90114. };
  90115. /**
  90116. * Execute the current task
  90117. * @param scene defines the scene where you want your assets to be loaded
  90118. * @param onSuccess is a callback called when the task is successfully executed
  90119. * @param onError is a callback called if an error occurs
  90120. */
  90121. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90122. var _this = this;
  90123. this._taskState = AssetTaskState.RUNNING;
  90124. this.runTask(scene, function () {
  90125. _this.onDoneCallback(onSuccess, onError);
  90126. }, function (msg, exception) {
  90127. _this.onErrorCallback(onError, msg, exception);
  90128. });
  90129. };
  90130. /**
  90131. * Execute the current task
  90132. * @param scene defines the scene where you want your assets to be loaded
  90133. * @param onSuccess is a callback called when the task is successfully executed
  90134. * @param onError is a callback called if an error occurs
  90135. */
  90136. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90137. throw new Error("runTask is not implemented");
  90138. };
  90139. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  90140. this._taskState = AssetTaskState.ERROR;
  90141. this._errorObject = {
  90142. message: message,
  90143. exception: exception
  90144. };
  90145. if (this.onError) {
  90146. this.onError(this, message, exception);
  90147. }
  90148. onError();
  90149. };
  90150. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  90151. try {
  90152. this._taskState = AssetTaskState.DONE;
  90153. this._isCompleted = true;
  90154. if (this.onSuccess) {
  90155. this.onSuccess(this);
  90156. }
  90157. onSuccess();
  90158. }
  90159. catch (e) {
  90160. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  90161. }
  90162. };
  90163. return AbstractAssetTask;
  90164. }());
  90165. BABYLON.AbstractAssetTask = AbstractAssetTask;
  90166. /**
  90167. * Class used to share progress information about assets loading
  90168. */
  90169. var AssetsProgressEvent = /** @class */ (function () {
  90170. /**
  90171. * Creates a {BABYLON.AssetsProgressEvent}
  90172. * @param remainingCount defines the number of remaining tasks to process
  90173. * @param totalCount defines the total number of tasks
  90174. * @param task defines the task that was just processed
  90175. */
  90176. function AssetsProgressEvent(remainingCount, totalCount, task) {
  90177. this.remainingCount = remainingCount;
  90178. this.totalCount = totalCount;
  90179. this.task = task;
  90180. }
  90181. return AssetsProgressEvent;
  90182. }());
  90183. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  90184. /**
  90185. * Define a task used by {BABYLON.AssetsManager} to load meshes
  90186. */
  90187. var MeshAssetTask = /** @class */ (function (_super) {
  90188. __extends(MeshAssetTask, _super);
  90189. /**
  90190. * Creates a new {BABYLON.MeshAssetTask}
  90191. * @param name defines the name of the task
  90192. * @param meshesNames defines the list of mesh's names you want to load
  90193. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  90194. * @param sceneFilename defines the filename of the scene to load from
  90195. */
  90196. function MeshAssetTask(
  90197. /**
  90198. * Defines the name of the task
  90199. */
  90200. name,
  90201. /**
  90202. * Defines the list of mesh's names you want to load
  90203. */
  90204. meshesNames,
  90205. /**
  90206. * Defines the root url to use as a base to load your meshes and associated resources
  90207. */
  90208. rootUrl,
  90209. /**
  90210. * Defines the filename of the scene to load from
  90211. */
  90212. sceneFilename) {
  90213. var _this = _super.call(this, name) || this;
  90214. _this.name = name;
  90215. _this.meshesNames = meshesNames;
  90216. _this.rootUrl = rootUrl;
  90217. _this.sceneFilename = sceneFilename;
  90218. return _this;
  90219. }
  90220. /**
  90221. * Execute the current task
  90222. * @param scene defines the scene where you want your assets to be loaded
  90223. * @param onSuccess is a callback called when the task is successfully executed
  90224. * @param onError is a callback called if an error occurs
  90225. */
  90226. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90227. var _this = this;
  90228. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  90229. _this.loadedMeshes = meshes;
  90230. _this.loadedParticleSystems = particleSystems;
  90231. _this.loadedSkeletons = skeletons;
  90232. onSuccess();
  90233. }, null, function (scene, message, exception) {
  90234. onError(message, exception);
  90235. });
  90236. };
  90237. return MeshAssetTask;
  90238. }(AbstractAssetTask));
  90239. BABYLON.MeshAssetTask = MeshAssetTask;
  90240. /**
  90241. * Define a task used by {BABYLON.AssetsManager} to load text content
  90242. */
  90243. var TextFileAssetTask = /** @class */ (function (_super) {
  90244. __extends(TextFileAssetTask, _super);
  90245. /**
  90246. * Creates a new TextFileAssetTask object
  90247. * @param name defines the name of the task
  90248. * @param url defines the location of the file to load
  90249. */
  90250. function TextFileAssetTask(
  90251. /**
  90252. * Defines the name of the task
  90253. */
  90254. name,
  90255. /**
  90256. * Defines the location of the file to load
  90257. */
  90258. url) {
  90259. var _this = _super.call(this, name) || this;
  90260. _this.name = name;
  90261. _this.url = url;
  90262. return _this;
  90263. }
  90264. /**
  90265. * Execute the current task
  90266. * @param scene defines the scene where you want your assets to be loaded
  90267. * @param onSuccess is a callback called when the task is successfully executed
  90268. * @param onError is a callback called if an error occurs
  90269. */
  90270. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90271. var _this = this;
  90272. scene._loadFile(this.url, function (data) {
  90273. _this.text = data;
  90274. onSuccess();
  90275. }, undefined, false, false, function (request, exception) {
  90276. if (request) {
  90277. onError(request.status + " " + request.statusText, exception);
  90278. }
  90279. });
  90280. };
  90281. return TextFileAssetTask;
  90282. }(AbstractAssetTask));
  90283. BABYLON.TextFileAssetTask = TextFileAssetTask;
  90284. /**
  90285. * Define a task used by {BABYLON.AssetsManager} to load binary data
  90286. */
  90287. var BinaryFileAssetTask = /** @class */ (function (_super) {
  90288. __extends(BinaryFileAssetTask, _super);
  90289. /**
  90290. * Creates a new BinaryFileAssetTask object
  90291. * @param name defines the name of the new task
  90292. * @param url defines the location of the file to load
  90293. */
  90294. function BinaryFileAssetTask(
  90295. /**
  90296. * Defines the name of the task
  90297. */
  90298. name,
  90299. /**
  90300. * Defines the location of the file to load
  90301. */
  90302. url) {
  90303. var _this = _super.call(this, name) || this;
  90304. _this.name = name;
  90305. _this.url = url;
  90306. return _this;
  90307. }
  90308. /**
  90309. * Execute the current task
  90310. * @param scene defines the scene where you want your assets to be loaded
  90311. * @param onSuccess is a callback called when the task is successfully executed
  90312. * @param onError is a callback called if an error occurs
  90313. */
  90314. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90315. var _this = this;
  90316. scene._loadFile(this.url, function (data) {
  90317. _this.data = data;
  90318. onSuccess();
  90319. }, undefined, true, true, function (request, exception) {
  90320. if (request) {
  90321. onError(request.status + " " + request.statusText, exception);
  90322. }
  90323. });
  90324. };
  90325. return BinaryFileAssetTask;
  90326. }(AbstractAssetTask));
  90327. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  90328. /**
  90329. * Define a task used by {BABYLON.AssetsManager} to load images
  90330. */
  90331. var ImageAssetTask = /** @class */ (function (_super) {
  90332. __extends(ImageAssetTask, _super);
  90333. /**
  90334. * Creates a new ImageAssetTask
  90335. * @param name defines the name of the task
  90336. * @param url defines the location of the image to load
  90337. */
  90338. function ImageAssetTask(
  90339. /**
  90340. * Defines the name of the task
  90341. */
  90342. name,
  90343. /**
  90344. * Defines the location of the image to load
  90345. */
  90346. url) {
  90347. var _this = _super.call(this, name) || this;
  90348. _this.name = name;
  90349. _this.url = url;
  90350. return _this;
  90351. }
  90352. /**
  90353. * Execute the current task
  90354. * @param scene defines the scene where you want your assets to be loaded
  90355. * @param onSuccess is a callback called when the task is successfully executed
  90356. * @param onError is a callback called if an error occurs
  90357. */
  90358. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90359. var _this = this;
  90360. var img = new Image();
  90361. BABYLON.Tools.SetCorsBehavior(this.url, img);
  90362. img.onload = function () {
  90363. _this.image = img;
  90364. onSuccess();
  90365. };
  90366. img.onerror = function (err) {
  90367. onError("Error loading image", err);
  90368. };
  90369. img.src = this.url;
  90370. };
  90371. return ImageAssetTask;
  90372. }(AbstractAssetTask));
  90373. BABYLON.ImageAssetTask = ImageAssetTask;
  90374. /**
  90375. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  90376. */
  90377. var TextureAssetTask = /** @class */ (function (_super) {
  90378. __extends(TextureAssetTask, _super);
  90379. /**
  90380. * Creates a new TextureAssetTask object
  90381. * @param name defines the name of the task
  90382. * @param url defines the location of the file to load
  90383. * @param noMipmap defines if mipmap should not be generated (default is false)
  90384. * @param invertY defines if texture must be inverted on Y axis (default is false)
  90385. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90386. */
  90387. function TextureAssetTask(
  90388. /**
  90389. * Defines the name of the task
  90390. */
  90391. name,
  90392. /**
  90393. * Defines the location of the file to load
  90394. */
  90395. url,
  90396. /**
  90397. * Defines if mipmap should not be generated (default is false)
  90398. */
  90399. noMipmap,
  90400. /**
  90401. * Defines if texture must be inverted on Y axis (default is false)
  90402. */
  90403. invertY,
  90404. /**
  90405. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90406. */
  90407. samplingMode) {
  90408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90409. var _this = _super.call(this, name) || this;
  90410. _this.name = name;
  90411. _this.url = url;
  90412. _this.noMipmap = noMipmap;
  90413. _this.invertY = invertY;
  90414. _this.samplingMode = samplingMode;
  90415. return _this;
  90416. }
  90417. /**
  90418. * Execute the current task
  90419. * @param scene defines the scene where you want your assets to be loaded
  90420. * @param onSuccess is a callback called when the task is successfully executed
  90421. * @param onError is a callback called if an error occurs
  90422. */
  90423. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90424. var onload = function () {
  90425. onSuccess();
  90426. };
  90427. var onerror = function (message, exception) {
  90428. onError(message, exception);
  90429. };
  90430. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  90431. };
  90432. return TextureAssetTask;
  90433. }(AbstractAssetTask));
  90434. BABYLON.TextureAssetTask = TextureAssetTask;
  90435. /**
  90436. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  90437. */
  90438. var CubeTextureAssetTask = /** @class */ (function (_super) {
  90439. __extends(CubeTextureAssetTask, _super);
  90440. /**
  90441. * Creates a new CubeTextureAssetTask
  90442. * @param name defines the name of the task
  90443. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90444. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90445. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90446. * @param files defines the explicit list of files (undefined by default)
  90447. */
  90448. function CubeTextureAssetTask(
  90449. /**
  90450. * Defines the name of the task
  90451. */
  90452. name,
  90453. /**
  90454. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90455. */
  90456. url,
  90457. /**
  90458. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90459. */
  90460. extensions,
  90461. /**
  90462. * Defines if mipmaps should not be generated (default is false)
  90463. */
  90464. noMipmap,
  90465. /**
  90466. * Defines the explicit list of files (undefined by default)
  90467. */
  90468. files) {
  90469. var _this = _super.call(this, name) || this;
  90470. _this.name = name;
  90471. _this.url = url;
  90472. _this.extensions = extensions;
  90473. _this.noMipmap = noMipmap;
  90474. _this.files = files;
  90475. return _this;
  90476. }
  90477. /**
  90478. * Execute the current task
  90479. * @param scene defines the scene where you want your assets to be loaded
  90480. * @param onSuccess is a callback called when the task is successfully executed
  90481. * @param onError is a callback called if an error occurs
  90482. */
  90483. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90484. var onload = function () {
  90485. onSuccess();
  90486. };
  90487. var onerror = function (message, exception) {
  90488. onError(message, exception);
  90489. };
  90490. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  90491. };
  90492. return CubeTextureAssetTask;
  90493. }(AbstractAssetTask));
  90494. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  90495. /**
  90496. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  90497. */
  90498. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  90499. __extends(HDRCubeTextureAssetTask, _super);
  90500. /**
  90501. * Creates a new HDRCubeTextureAssetTask object
  90502. * @param name defines the name of the task
  90503. * @param url defines the location of the file to load
  90504. * @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.
  90505. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90506. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  90507. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  90508. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  90509. */
  90510. function HDRCubeTextureAssetTask(
  90511. /**
  90512. * Defines the name of the task
  90513. */
  90514. name,
  90515. /**
  90516. * Defines the location of the file to load
  90517. */
  90518. url,
  90519. /**
  90520. * 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.
  90521. */
  90522. size,
  90523. /**
  90524. * Defines if mipmaps should not be generated (default is false)
  90525. */
  90526. noMipmap,
  90527. /**
  90528. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  90529. */
  90530. generateHarmonics,
  90531. /**
  90532. * 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)
  90533. */
  90534. useInGammaSpace,
  90535. /**
  90536. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  90537. */
  90538. usePMREMGenerator) {
  90539. if (noMipmap === void 0) { noMipmap = false; }
  90540. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90541. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  90542. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  90543. var _this = _super.call(this, name) || this;
  90544. _this.name = name;
  90545. _this.url = url;
  90546. _this.size = size;
  90547. _this.noMipmap = noMipmap;
  90548. _this.generateHarmonics = generateHarmonics;
  90549. _this.useInGammaSpace = useInGammaSpace;
  90550. _this.usePMREMGenerator = usePMREMGenerator;
  90551. return _this;
  90552. }
  90553. /**
  90554. * Execute the current task
  90555. * @param scene defines the scene where you want your assets to be loaded
  90556. * @param onSuccess is a callback called when the task is successfully executed
  90557. * @param onError is a callback called if an error occurs
  90558. */
  90559. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90560. var onload = function () {
  90561. onSuccess();
  90562. };
  90563. var onerror = function (message, exception) {
  90564. onError(message, exception);
  90565. };
  90566. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  90567. };
  90568. return HDRCubeTextureAssetTask;
  90569. }(AbstractAssetTask));
  90570. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  90571. /**
  90572. * This class can be used to easily import assets into a scene
  90573. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  90574. */
  90575. var AssetsManager = /** @class */ (function () {
  90576. /**
  90577. * Creates a new AssetsManager
  90578. * @param scene defines the scene to work on
  90579. */
  90580. function AssetsManager(scene) {
  90581. this._isLoading = false;
  90582. this._tasks = new Array();
  90583. this._waitingTasksCount = 0;
  90584. this._totalTasksCount = 0;
  90585. /**
  90586. * Observable called when all tasks are processed
  90587. */
  90588. this.onTaskSuccessObservable = new BABYLON.Observable();
  90589. /**
  90590. * Observable called when a task had an error
  90591. */
  90592. this.onTaskErrorObservable = new BABYLON.Observable();
  90593. /**
  90594. * Observable called when a task is successful
  90595. */
  90596. this.onTasksDoneObservable = new BABYLON.Observable();
  90597. /**
  90598. * Observable called when a task is done (whatever the result is)
  90599. */
  90600. this.onProgressObservable = new BABYLON.Observable();
  90601. /**
  90602. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  90603. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  90604. */
  90605. this.useDefaultLoadingScreen = true;
  90606. this._scene = scene;
  90607. }
  90608. /**
  90609. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  90610. * @param taskName defines the name of the new task
  90611. * @param meshesNames defines the name of meshes to load
  90612. * @param rootUrl defines the root url to use to locate files
  90613. * @param sceneFilename defines the filename of the scene file
  90614. * @returns a new {BABYLON.MeshAssetTask} object
  90615. */
  90616. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  90617. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  90618. this._tasks.push(task);
  90619. return task;
  90620. };
  90621. /**
  90622. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  90623. * @param taskName defines the name of the new task
  90624. * @param url defines the url of the file to load
  90625. * @returns a new {BABYLON.TextFileAssetTask} object
  90626. */
  90627. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  90628. var task = new TextFileAssetTask(taskName, url);
  90629. this._tasks.push(task);
  90630. return task;
  90631. };
  90632. /**
  90633. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  90634. * @param taskName defines the name of the new task
  90635. * @param url defines the url of the file to load
  90636. * @returns a new {BABYLON.BinaryFileAssetTask} object
  90637. */
  90638. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  90639. var task = new BinaryFileAssetTask(taskName, url);
  90640. this._tasks.push(task);
  90641. return task;
  90642. };
  90643. /**
  90644. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  90645. * @param taskName defines the name of the new task
  90646. * @param url defines the url of the file to load
  90647. * @returns a new {BABYLON.ImageAssetTask} object
  90648. */
  90649. AssetsManager.prototype.addImageTask = function (taskName, url) {
  90650. var task = new ImageAssetTask(taskName, url);
  90651. this._tasks.push(task);
  90652. return task;
  90653. };
  90654. /**
  90655. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  90656. * @param taskName defines the name of the new task
  90657. * @param url defines the url of the file to load
  90658. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90659. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  90660. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  90661. * @returns a new {BABYLON.TextureAssetTask} object
  90662. */
  90663. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  90664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90665. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  90666. this._tasks.push(task);
  90667. return task;
  90668. };
  90669. /**
  90670. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  90671. * @param taskName defines the name of the new task
  90672. * @param url defines the url of the file to load
  90673. * @param extensions defines the extension to use to load the cube map (can be null)
  90674. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90675. * @param files defines the list of files to load (can be null)
  90676. * @returns a new {BABYLON.CubeTextureAssetTask} object
  90677. */
  90678. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  90679. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  90680. this._tasks.push(task);
  90681. return task;
  90682. };
  90683. /**
  90684. *
  90685. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  90686. * @param taskName defines the name of the new task
  90687. * @param url defines the url of the file to load
  90688. * @param size defines the size you want for the cubemap (can be null)
  90689. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90690. * @param generateHarmonics defines if you want to automatically generate (true by default)
  90691. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  90692. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  90693. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  90694. */
  90695. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  90696. if (noMipmap === void 0) { noMipmap = false; }
  90697. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90698. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  90699. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  90700. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  90701. this._tasks.push(task);
  90702. return task;
  90703. };
  90704. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  90705. var _this = this;
  90706. this._waitingTasksCount--;
  90707. try {
  90708. if (task.taskState === AssetTaskState.DONE) {
  90709. // Let's remove successfull tasks
  90710. BABYLON.Tools.SetImmediate(function () {
  90711. var index = _this._tasks.indexOf(task);
  90712. if (index > -1) {
  90713. _this._tasks.splice(index, 1);
  90714. }
  90715. });
  90716. }
  90717. if (this.onProgress) {
  90718. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  90719. }
  90720. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  90721. }
  90722. catch (e) {
  90723. BABYLON.Tools.Error("Error running progress callbacks.");
  90724. console.log(e);
  90725. }
  90726. if (this._waitingTasksCount === 0) {
  90727. try {
  90728. if (this.onFinish) {
  90729. this.onFinish(this._tasks);
  90730. }
  90731. this.onTasksDoneObservable.notifyObservers(this._tasks);
  90732. }
  90733. catch (e) {
  90734. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  90735. console.log(e);
  90736. }
  90737. this._isLoading = false;
  90738. this._scene.getEngine().hideLoadingUI();
  90739. }
  90740. };
  90741. AssetsManager.prototype._runTask = function (task) {
  90742. var _this = this;
  90743. var done = function () {
  90744. try {
  90745. if (_this.onTaskSuccess) {
  90746. _this.onTaskSuccess(task);
  90747. }
  90748. _this.onTaskSuccessObservable.notifyObservers(task);
  90749. _this._decreaseWaitingTasksCount(task);
  90750. }
  90751. catch (e) {
  90752. error("Error executing task success callbacks", e);
  90753. }
  90754. };
  90755. var error = function (message, exception) {
  90756. task._setErrorObject(message, exception);
  90757. if (_this.onTaskError) {
  90758. _this.onTaskError(task);
  90759. }
  90760. _this.onTaskErrorObservable.notifyObservers(task);
  90761. _this._decreaseWaitingTasksCount(task);
  90762. };
  90763. task.run(this._scene, done, error);
  90764. };
  90765. /**
  90766. * Reset the {BABYLON.AssetsManager} and remove all tasks
  90767. * @return the current instance of the {BABYLON.AssetsManager}
  90768. */
  90769. AssetsManager.prototype.reset = function () {
  90770. this._isLoading = false;
  90771. this._tasks = new Array();
  90772. return this;
  90773. };
  90774. /**
  90775. * Start the loading process
  90776. * @return the current instance of the {BABYLON.AssetsManager}
  90777. */
  90778. AssetsManager.prototype.load = function () {
  90779. if (this._isLoading) {
  90780. return this;
  90781. }
  90782. this._isLoading = true;
  90783. this._waitingTasksCount = this._tasks.length;
  90784. this._totalTasksCount = this._tasks.length;
  90785. if (this._waitingTasksCount === 0) {
  90786. this._isLoading = false;
  90787. if (this.onFinish) {
  90788. this.onFinish(this._tasks);
  90789. }
  90790. this.onTasksDoneObservable.notifyObservers(this._tasks);
  90791. return this;
  90792. }
  90793. if (this.useDefaultLoadingScreen) {
  90794. this._scene.getEngine().displayLoadingUI();
  90795. }
  90796. for (var index = 0; index < this._tasks.length; index++) {
  90797. var task = this._tasks[index];
  90798. this._runTask(task);
  90799. }
  90800. return this;
  90801. };
  90802. return AssetsManager;
  90803. }());
  90804. BABYLON.AssetsManager = AssetsManager;
  90805. })(BABYLON || (BABYLON = {}));
  90806. //# sourceMappingURL=babylon.assetsManager.js.map
  90807. "use strict";
  90808. var BABYLON;
  90809. (function (BABYLON) {
  90810. var serializedGeometries = [];
  90811. var serializeGeometry = function (geometry, serializationGeometries) {
  90812. if (serializedGeometries[geometry.id]) {
  90813. return;
  90814. }
  90815. if (geometry.doNotSerialize) {
  90816. return;
  90817. }
  90818. if (geometry instanceof BABYLON.BoxGeometry) {
  90819. serializationGeometries.boxes.push(geometry.serialize());
  90820. }
  90821. else if (geometry instanceof BABYLON.SphereGeometry) {
  90822. serializationGeometries.spheres.push(geometry.serialize());
  90823. }
  90824. else if (geometry instanceof BABYLON.CylinderGeometry) {
  90825. serializationGeometries.cylinders.push(geometry.serialize());
  90826. }
  90827. else if (geometry instanceof BABYLON.TorusGeometry) {
  90828. serializationGeometries.toruses.push(geometry.serialize());
  90829. }
  90830. else if (geometry instanceof BABYLON.GroundGeometry) {
  90831. serializationGeometries.grounds.push(geometry.serialize());
  90832. }
  90833. else if (geometry instanceof BABYLON.Plane) {
  90834. serializationGeometries.planes.push(geometry.serialize());
  90835. }
  90836. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  90837. serializationGeometries.torusKnots.push(geometry.serialize());
  90838. }
  90839. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  90840. throw new Error("Unknown primitive type");
  90841. }
  90842. else {
  90843. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  90844. }
  90845. serializedGeometries[geometry.id] = true;
  90846. };
  90847. var serializeMesh = function (mesh, serializationScene) {
  90848. var serializationObject = {};
  90849. // Geometry
  90850. var geometry = mesh._geometry;
  90851. if (geometry) {
  90852. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  90853. // 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
  90854. serializeGeometry(geometry, serializationScene.geometries);
  90855. }
  90856. }
  90857. // Custom
  90858. if (mesh.serialize) {
  90859. mesh.serialize(serializationObject);
  90860. }
  90861. return serializationObject;
  90862. };
  90863. var finalizeSingleMesh = function (mesh, serializationObject) {
  90864. //only works if the mesh is already loaded
  90865. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  90866. //serialize material
  90867. if (mesh.material) {
  90868. if (mesh.material instanceof BABYLON.StandardMaterial) {
  90869. serializationObject.materials = serializationObject.materials || [];
  90870. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  90871. serializationObject.materials.push(mesh.material.serialize());
  90872. }
  90873. }
  90874. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  90875. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  90876. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  90877. serializationObject.multiMaterials.push(mesh.material.serialize());
  90878. }
  90879. }
  90880. }
  90881. //serialize geometry
  90882. var geometry = mesh._geometry;
  90883. if (geometry) {
  90884. if (!serializationObject.geometries) {
  90885. serializationObject.geometries = {};
  90886. serializationObject.geometries.boxes = [];
  90887. serializationObject.geometries.spheres = [];
  90888. serializationObject.geometries.cylinders = [];
  90889. serializationObject.geometries.toruses = [];
  90890. serializationObject.geometries.grounds = [];
  90891. serializationObject.geometries.planes = [];
  90892. serializationObject.geometries.torusKnots = [];
  90893. serializationObject.geometries.vertexData = [];
  90894. }
  90895. serializeGeometry(geometry, serializationObject.geometries);
  90896. }
  90897. // Skeletons
  90898. if (mesh.skeleton) {
  90899. serializationObject.skeletons = serializationObject.skeletons || [];
  90900. serializationObject.skeletons.push(mesh.skeleton.serialize());
  90901. }
  90902. //serialize the actual mesh
  90903. serializationObject.meshes = serializationObject.meshes || [];
  90904. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  90905. }
  90906. };
  90907. var SceneSerializer = /** @class */ (function () {
  90908. function SceneSerializer() {
  90909. }
  90910. SceneSerializer.ClearCache = function () {
  90911. serializedGeometries = [];
  90912. };
  90913. SceneSerializer.Serialize = function (scene) {
  90914. var serializationObject = {};
  90915. SceneSerializer.ClearCache();
  90916. // Scene
  90917. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  90918. serializationObject.autoClear = scene.autoClear;
  90919. serializationObject.clearColor = scene.clearColor.asArray();
  90920. serializationObject.ambientColor = scene.ambientColor.asArray();
  90921. serializationObject.gravity = scene.gravity.asArray();
  90922. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  90923. serializationObject.workerCollisions = scene.workerCollisions;
  90924. // Fog
  90925. if (scene.fogMode && scene.fogMode !== 0) {
  90926. serializationObject.fogMode = scene.fogMode;
  90927. serializationObject.fogColor = scene.fogColor.asArray();
  90928. serializationObject.fogStart = scene.fogStart;
  90929. serializationObject.fogEnd = scene.fogEnd;
  90930. serializationObject.fogDensity = scene.fogDensity;
  90931. }
  90932. //Physics
  90933. if (scene.isPhysicsEnabled()) {
  90934. var physicEngine = scene.getPhysicsEngine();
  90935. if (physicEngine) {
  90936. serializationObject.physicsEnabled = true;
  90937. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  90938. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  90939. }
  90940. }
  90941. // Metadata
  90942. if (scene.metadata) {
  90943. serializationObject.metadata = scene.metadata;
  90944. }
  90945. // Morph targets
  90946. serializationObject.morphTargetManagers = [];
  90947. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  90948. var abstractMesh = _a[_i];
  90949. var manager = abstractMesh.morphTargetManager;
  90950. if (manager) {
  90951. serializationObject.morphTargetManagers.push(manager.serialize());
  90952. }
  90953. }
  90954. // Lights
  90955. serializationObject.lights = [];
  90956. var index;
  90957. var light;
  90958. for (index = 0; index < scene.lights.length; index++) {
  90959. light = scene.lights[index];
  90960. if (!light.doNotSerialize) {
  90961. serializationObject.lights.push(light.serialize());
  90962. }
  90963. }
  90964. // Cameras
  90965. serializationObject.cameras = [];
  90966. for (index = 0; index < scene.cameras.length; index++) {
  90967. var camera = scene.cameras[index];
  90968. if (!camera.doNotSerialize) {
  90969. serializationObject.cameras.push(camera.serialize());
  90970. }
  90971. }
  90972. if (scene.activeCamera) {
  90973. serializationObject.activeCameraID = scene.activeCamera.id;
  90974. }
  90975. // Animations
  90976. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  90977. // Materials
  90978. serializationObject.materials = [];
  90979. serializationObject.multiMaterials = [];
  90980. var material;
  90981. for (index = 0; index < scene.materials.length; index++) {
  90982. material = scene.materials[index];
  90983. if (!material.doNotSerialize) {
  90984. serializationObject.materials.push(material.serialize());
  90985. }
  90986. }
  90987. // MultiMaterials
  90988. serializationObject.multiMaterials = [];
  90989. for (index = 0; index < scene.multiMaterials.length; index++) {
  90990. var multiMaterial = scene.multiMaterials[index];
  90991. serializationObject.multiMaterials.push(multiMaterial.serialize());
  90992. }
  90993. // Environment texture
  90994. if (scene.environmentTexture) {
  90995. serializationObject.environmentTexture = scene.environmentTexture.name;
  90996. }
  90997. // Skeletons
  90998. serializationObject.skeletons = [];
  90999. for (index = 0; index < scene.skeletons.length; index++) {
  91000. var skeleton = scene.skeletons[index];
  91001. if (!skeleton.doNotSerialize) {
  91002. serializationObject.skeletons.push(skeleton.serialize());
  91003. }
  91004. }
  91005. // Transform nodes
  91006. serializationObject.transformNodes = [];
  91007. for (index = 0; index < scene.transformNodes.length; index++) {
  91008. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  91009. }
  91010. // Geometries
  91011. serializationObject.geometries = {};
  91012. serializationObject.geometries.boxes = [];
  91013. serializationObject.geometries.spheres = [];
  91014. serializationObject.geometries.cylinders = [];
  91015. serializationObject.geometries.toruses = [];
  91016. serializationObject.geometries.grounds = [];
  91017. serializationObject.geometries.planes = [];
  91018. serializationObject.geometries.torusKnots = [];
  91019. serializationObject.geometries.vertexData = [];
  91020. serializedGeometries = [];
  91021. var geometries = scene.getGeometries();
  91022. for (index = 0; index < geometries.length; index++) {
  91023. var geometry = geometries[index];
  91024. if (geometry.isReady()) {
  91025. serializeGeometry(geometry, serializationObject.geometries);
  91026. }
  91027. }
  91028. // Meshes
  91029. serializationObject.meshes = [];
  91030. for (index = 0; index < scene.meshes.length; index++) {
  91031. var abstractMesh = scene.meshes[index];
  91032. if (abstractMesh instanceof BABYLON.Mesh) {
  91033. var mesh = abstractMesh;
  91034. if (!mesh.doNotSerialize) {
  91035. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91036. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91037. }
  91038. }
  91039. }
  91040. }
  91041. // Particles Systems
  91042. serializationObject.particleSystems = [];
  91043. for (index = 0; index < scene.particleSystems.length; index++) {
  91044. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  91045. }
  91046. // Lens flares
  91047. serializationObject.lensFlareSystems = [];
  91048. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  91049. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  91050. }
  91051. // Shadows
  91052. serializationObject.shadowGenerators = [];
  91053. for (index = 0; index < scene.lights.length; index++) {
  91054. light = scene.lights[index];
  91055. var shadowGenerator = light.getShadowGenerator();
  91056. if (shadowGenerator) {
  91057. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  91058. }
  91059. }
  91060. // Action Manager
  91061. if (scene.actionManager) {
  91062. serializationObject.actions = scene.actionManager.serialize("scene");
  91063. }
  91064. // Audio
  91065. serializationObject.sounds = [];
  91066. for (index = 0; index < scene.soundTracks.length; index++) {
  91067. var soundtrack = scene.soundTracks[index];
  91068. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  91069. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  91070. }
  91071. }
  91072. return serializationObject;
  91073. };
  91074. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  91075. if (withParents === void 0) { withParents = false; }
  91076. if (withChildren === void 0) { withChildren = false; }
  91077. var serializationObject = {};
  91078. SceneSerializer.ClearCache();
  91079. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  91080. if (withParents || withChildren) {
  91081. //deliberate for loop! not for each, appended should be processed as well.
  91082. for (var i = 0; i < toSerialize.length; ++i) {
  91083. if (withChildren) {
  91084. toSerialize[i].getDescendants().forEach(function (node) {
  91085. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  91086. toSerialize.push(node);
  91087. }
  91088. });
  91089. }
  91090. //make sure the array doesn't contain the object already
  91091. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  91092. toSerialize.push(toSerialize[i].parent);
  91093. }
  91094. }
  91095. }
  91096. toSerialize.forEach(function (mesh) {
  91097. finalizeSingleMesh(mesh, serializationObject);
  91098. });
  91099. return serializationObject;
  91100. };
  91101. return SceneSerializer;
  91102. }());
  91103. BABYLON.SceneSerializer = SceneSerializer;
  91104. })(BABYLON || (BABYLON = {}));
  91105. //# sourceMappingURL=babylon.sceneSerializer.js.map
  91106. "use strict";
  91107. var BABYLON;
  91108. (function (BABYLON) {
  91109. var ReflectionProbe = /** @class */ (function () {
  91110. function ReflectionProbe(name, size, scene, generateMipMaps) {
  91111. if (generateMipMaps === void 0) { generateMipMaps = true; }
  91112. var _this = this;
  91113. this.name = name;
  91114. this._viewMatrix = BABYLON.Matrix.Identity();
  91115. this._target = BABYLON.Vector3.Zero();
  91116. this._add = BABYLON.Vector3.Zero();
  91117. this._invertYAxis = false;
  91118. this.position = BABYLON.Vector3.Zero();
  91119. this._scene = scene;
  91120. this._scene.reflectionProbes.push(this);
  91121. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  91122. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  91123. switch (faceIndex) {
  91124. case 0:
  91125. _this._add.copyFromFloats(1, 0, 0);
  91126. break;
  91127. case 1:
  91128. _this._add.copyFromFloats(-1, 0, 0);
  91129. break;
  91130. case 2:
  91131. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  91132. break;
  91133. case 3:
  91134. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  91135. break;
  91136. case 4:
  91137. _this._add.copyFromFloats(0, 0, 1);
  91138. break;
  91139. case 5:
  91140. _this._add.copyFromFloats(0, 0, -1);
  91141. break;
  91142. }
  91143. if (_this._attachedMesh) {
  91144. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  91145. }
  91146. _this.position.addToRef(_this._add, _this._target);
  91147. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  91148. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  91149. scene._forcedViewPosition = _this.position;
  91150. });
  91151. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  91152. scene._forcedViewPosition = null;
  91153. scene.updateTransformMatrix(true);
  91154. });
  91155. if (scene.activeCamera) {
  91156. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  91157. }
  91158. }
  91159. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  91160. get: function () {
  91161. return this._renderTargetTexture.samples;
  91162. },
  91163. set: function (value) {
  91164. this._renderTargetTexture.samples = value;
  91165. },
  91166. enumerable: true,
  91167. configurable: true
  91168. });
  91169. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  91170. get: function () {
  91171. return this._renderTargetTexture.refreshRate;
  91172. },
  91173. set: function (value) {
  91174. this._renderTargetTexture.refreshRate = value;
  91175. },
  91176. enumerable: true,
  91177. configurable: true
  91178. });
  91179. ReflectionProbe.prototype.getScene = function () {
  91180. return this._scene;
  91181. };
  91182. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  91183. get: function () {
  91184. return this._renderTargetTexture;
  91185. },
  91186. enumerable: true,
  91187. configurable: true
  91188. });
  91189. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  91190. get: function () {
  91191. return this._renderTargetTexture.renderList;
  91192. },
  91193. enumerable: true,
  91194. configurable: true
  91195. });
  91196. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  91197. this._attachedMesh = mesh;
  91198. };
  91199. /**
  91200. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  91201. *
  91202. * @param renderingGroupId The rendering group id corresponding to its index
  91203. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  91204. */
  91205. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  91206. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  91207. };
  91208. ReflectionProbe.prototype.dispose = function () {
  91209. var index = this._scene.reflectionProbes.indexOf(this);
  91210. if (index !== -1) {
  91211. // Remove from the scene if found
  91212. this._scene.reflectionProbes.splice(index, 1);
  91213. }
  91214. if (this._renderTargetTexture) {
  91215. this._renderTargetTexture.dispose();
  91216. this._renderTargetTexture = null;
  91217. }
  91218. };
  91219. return ReflectionProbe;
  91220. }());
  91221. BABYLON.ReflectionProbe = ReflectionProbe;
  91222. })(BABYLON || (BABYLON = {}));
  91223. //# sourceMappingURL=babylon.reflectionProbe.js.map
  91224. "use strict";
  91225. var BABYLON;
  91226. (function (BABYLON) {
  91227. var Layer = /** @class */ (function () {
  91228. function Layer(name, imgUrl, scene, isBackground, color) {
  91229. this.name = name;
  91230. this.scale = new BABYLON.Vector2(1, 1);
  91231. this.offset = new BABYLON.Vector2(0, 0);
  91232. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  91233. this.layerMask = 0x0FFFFFFF;
  91234. this._vertexBuffers = {};
  91235. // Events
  91236. /**
  91237. * An event triggered when the layer is disposed.
  91238. */
  91239. this.onDisposeObservable = new BABYLON.Observable();
  91240. /**
  91241. * An event triggered before rendering the scene
  91242. */
  91243. this.onBeforeRenderObservable = new BABYLON.Observable();
  91244. /**
  91245. * An event triggered after rendering the scene
  91246. */
  91247. this.onAfterRenderObservable = new BABYLON.Observable();
  91248. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  91249. this.isBackground = isBackground === undefined ? true : isBackground;
  91250. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  91251. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  91252. this._scene.layers.push(this);
  91253. var engine = this._scene.getEngine();
  91254. // VBO
  91255. var vertices = [];
  91256. vertices.push(1, 1);
  91257. vertices.push(-1, 1);
  91258. vertices.push(-1, -1);
  91259. vertices.push(1, -1);
  91260. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91262. this._createIndexBuffer();
  91263. // Effects
  91264. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  91265. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  91266. }
  91267. Object.defineProperty(Layer.prototype, "onDispose", {
  91268. set: function (callback) {
  91269. if (this._onDisposeObserver) {
  91270. this.onDisposeObservable.remove(this._onDisposeObserver);
  91271. }
  91272. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91273. },
  91274. enumerable: true,
  91275. configurable: true
  91276. });
  91277. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  91278. set: function (callback) {
  91279. if (this._onBeforeRenderObserver) {
  91280. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  91281. }
  91282. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  91283. },
  91284. enumerable: true,
  91285. configurable: true
  91286. });
  91287. Object.defineProperty(Layer.prototype, "onAfterRender", {
  91288. set: function (callback) {
  91289. if (this._onAfterRenderObserver) {
  91290. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91291. }
  91292. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  91293. },
  91294. enumerable: true,
  91295. configurable: true
  91296. });
  91297. Layer.prototype._createIndexBuffer = function () {
  91298. var engine = this._scene.getEngine();
  91299. // Indices
  91300. var indices = [];
  91301. indices.push(0);
  91302. indices.push(1);
  91303. indices.push(2);
  91304. indices.push(0);
  91305. indices.push(2);
  91306. indices.push(3);
  91307. this._indexBuffer = engine.createIndexBuffer(indices);
  91308. };
  91309. Layer.prototype._rebuild = function () {
  91310. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91311. if (vb) {
  91312. vb._rebuild();
  91313. }
  91314. this._createIndexBuffer();
  91315. };
  91316. Layer.prototype.render = function () {
  91317. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  91318. // Check
  91319. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  91320. return;
  91321. var engine = this._scene.getEngine();
  91322. this.onBeforeRenderObservable.notifyObservers(this);
  91323. // Render
  91324. engine.enableEffect(currentEffect);
  91325. engine.setState(false);
  91326. // Texture
  91327. currentEffect.setTexture("textureSampler", this.texture);
  91328. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  91329. // Color
  91330. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  91331. // Scale / offset
  91332. currentEffect.setVector2("offset", this.offset);
  91333. currentEffect.setVector2("scale", this.scale);
  91334. // VBOs
  91335. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91336. // Draw order
  91337. if (!this.alphaTest) {
  91338. engine.setAlphaMode(this.alphaBlendingMode);
  91339. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91340. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91341. }
  91342. else {
  91343. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91344. }
  91345. this.onAfterRenderObservable.notifyObservers(this);
  91346. };
  91347. Layer.prototype.dispose = function () {
  91348. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91349. if (vertexBuffer) {
  91350. vertexBuffer.dispose();
  91351. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91352. }
  91353. if (this._indexBuffer) {
  91354. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91355. this._indexBuffer = null;
  91356. }
  91357. if (this.texture) {
  91358. this.texture.dispose();
  91359. this.texture = null;
  91360. }
  91361. // Remove from scene
  91362. var index = this._scene.layers.indexOf(this);
  91363. this._scene.layers.splice(index, 1);
  91364. // Callback
  91365. this.onDisposeObservable.notifyObservers(this);
  91366. this.onDisposeObservable.clear();
  91367. this.onAfterRenderObservable.clear();
  91368. this.onBeforeRenderObservable.clear();
  91369. };
  91370. return Layer;
  91371. }());
  91372. BABYLON.Layer = Layer;
  91373. })(BABYLON || (BABYLON = {}));
  91374. //# sourceMappingURL=babylon.layer.js.map
  91375. "use strict";
  91376. var BABYLON;
  91377. (function (BABYLON) {
  91378. var TextureTools = /** @class */ (function () {
  91379. function TextureTools() {
  91380. }
  91381. /**
  91382. * Uses the GPU to create a copy texture rescaled at a given size
  91383. * @param texture Texture to copy from
  91384. * @param width Desired width
  91385. * @param height Desired height
  91386. * @return Generated texture
  91387. */
  91388. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  91389. if (useBilinearMode === void 0) { useBilinearMode = true; }
  91390. var scene = texture.getScene();
  91391. var engine = scene.getEngine();
  91392. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  91393. rtt.wrapU = texture.wrapU;
  91394. rtt.wrapV = texture.wrapV;
  91395. rtt.uOffset = texture.uOffset;
  91396. rtt.vOffset = texture.vOffset;
  91397. rtt.uScale = texture.uScale;
  91398. rtt.vScale = texture.vScale;
  91399. rtt.uAng = texture.uAng;
  91400. rtt.vAng = texture.vAng;
  91401. rtt.wAng = texture.wAng;
  91402. rtt.coordinatesIndex = texture.coordinatesIndex;
  91403. rtt.level = texture.level;
  91404. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  91405. rtt._texture.isReady = false;
  91406. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91407. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91408. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91409. passPostProcess.getEffect().executeWhenCompiled(function () {
  91410. passPostProcess.onApply = function (effect) {
  91411. effect.setTexture("textureSampler", texture);
  91412. };
  91413. var internalTexture = rtt.getInternalTexture();
  91414. if (internalTexture) {
  91415. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  91416. engine.unBindFramebuffer(internalTexture);
  91417. rtt.disposeFramebufferObjects();
  91418. passPostProcess.dispose();
  91419. internalTexture.isReady = true;
  91420. }
  91421. });
  91422. return rtt;
  91423. };
  91424. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  91425. if (!scene._environmentBRDFTexture) {
  91426. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91427. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91428. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91429. scene._environmentBRDFTexture = texture;
  91430. }
  91431. return scene._environmentBRDFTexture;
  91432. };
  91433. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  91434. return TextureTools;
  91435. }());
  91436. BABYLON.TextureTools = TextureTools;
  91437. })(BABYLON || (BABYLON = {}));
  91438. //# sourceMappingURL=babylon.textureTools.js.map
  91439. "use strict";
  91440. var BABYLON;
  91441. (function (BABYLON) {
  91442. var FramingBehavior = /** @class */ (function () {
  91443. function FramingBehavior() {
  91444. this._mode = FramingBehavior.FitFrustumSidesMode;
  91445. this._radiusScale = 1.0;
  91446. this._positionScale = 0.5;
  91447. this._defaultElevation = 0.3;
  91448. this._elevationReturnTime = 1500;
  91449. this._elevationReturnWaitTime = 1000;
  91450. this._zoomStopsAnimation = false;
  91451. this._framingTime = 1500;
  91452. this._isPointerDown = false;
  91453. this._lastInteractionTime = -Infinity;
  91454. // Framing control
  91455. this._animatables = new Array();
  91456. this._betaIsAnimating = false;
  91457. }
  91458. Object.defineProperty(FramingBehavior.prototype, "name", {
  91459. get: function () {
  91460. return "Framing";
  91461. },
  91462. enumerable: true,
  91463. configurable: true
  91464. });
  91465. Object.defineProperty(FramingBehavior.prototype, "mode", {
  91466. /**
  91467. * Gets current mode used by the behavior.
  91468. */
  91469. get: function () {
  91470. return this._mode;
  91471. },
  91472. /**
  91473. * Sets the current mode used by the behavior
  91474. */
  91475. set: function (mode) {
  91476. this._mode = mode;
  91477. },
  91478. enumerable: true,
  91479. configurable: true
  91480. });
  91481. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  91482. /**
  91483. * Gets the scale applied to the radius
  91484. */
  91485. get: function () {
  91486. return this._radiusScale;
  91487. },
  91488. /**
  91489. * Sets the scale applied to the radius (1 by default)
  91490. */
  91491. set: function (radius) {
  91492. this._radiusScale = radius;
  91493. },
  91494. enumerable: true,
  91495. configurable: true
  91496. });
  91497. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  91498. /**
  91499. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  91500. */
  91501. get: function () {
  91502. return this._positionScale;
  91503. },
  91504. /**
  91505. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  91506. */
  91507. set: function (scale) {
  91508. this._positionScale = scale;
  91509. },
  91510. enumerable: true,
  91511. configurable: true
  91512. });
  91513. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  91514. /**
  91515. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  91516. * behaviour is triggered, in radians.
  91517. */
  91518. get: function () {
  91519. return this._defaultElevation;
  91520. },
  91521. /**
  91522. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  91523. * behaviour is triggered, in radians.
  91524. */
  91525. set: function (elevation) {
  91526. this._defaultElevation = elevation;
  91527. },
  91528. enumerable: true,
  91529. configurable: true
  91530. });
  91531. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  91532. /**
  91533. * Gets the time (in milliseconds) taken to return to the default beta position.
  91534. * Negative value indicates camera should not return to default.
  91535. */
  91536. get: function () {
  91537. return this._elevationReturnTime;
  91538. },
  91539. /**
  91540. * Sets the time (in milliseconds) taken to return to the default beta position.
  91541. * Negative value indicates camera should not return to default.
  91542. */
  91543. set: function (speed) {
  91544. this._elevationReturnTime = speed;
  91545. },
  91546. enumerable: true,
  91547. configurable: true
  91548. });
  91549. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  91550. /**
  91551. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  91552. */
  91553. get: function () {
  91554. return this._elevationReturnWaitTime;
  91555. },
  91556. /**
  91557. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  91558. */
  91559. set: function (time) {
  91560. this._elevationReturnWaitTime = time;
  91561. },
  91562. enumerable: true,
  91563. configurable: true
  91564. });
  91565. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  91566. /**
  91567. * Gets the flag that indicates if user zooming should stop animation.
  91568. */
  91569. get: function () {
  91570. return this._zoomStopsAnimation;
  91571. },
  91572. /**
  91573. * Sets the flag that indicates if user zooming should stop animation.
  91574. */
  91575. set: function (flag) {
  91576. this._zoomStopsAnimation = flag;
  91577. },
  91578. enumerable: true,
  91579. configurable: true
  91580. });
  91581. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  91582. /**
  91583. * Gets the transition time when framing the mesh, in milliseconds
  91584. */
  91585. get: function () {
  91586. return this._framingTime;
  91587. },
  91588. /**
  91589. * Sets the transition time when framing the mesh, in milliseconds
  91590. */
  91591. set: function (time) {
  91592. this._framingTime = time;
  91593. },
  91594. enumerable: true,
  91595. configurable: true
  91596. });
  91597. FramingBehavior.prototype.init = function () {
  91598. // Do notihng
  91599. };
  91600. FramingBehavior.prototype.attach = function (camera) {
  91601. var _this = this;
  91602. this._attachedCamera = camera;
  91603. var scene = this._attachedCamera.getScene();
  91604. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  91605. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  91606. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91607. _this._isPointerDown = true;
  91608. return;
  91609. }
  91610. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  91611. _this._isPointerDown = false;
  91612. }
  91613. });
  91614. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  91615. if (mesh) {
  91616. _this.zoomOnMesh(mesh);
  91617. }
  91618. });
  91619. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  91620. // Stop the animation if there is user interaction and the animation should stop for this interaction
  91621. _this._applyUserInteraction();
  91622. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  91623. // back to the default position after a given timeout
  91624. _this._maintainCameraAboveGround();
  91625. });
  91626. };
  91627. FramingBehavior.prototype.detach = function () {
  91628. if (!this._attachedCamera) {
  91629. return;
  91630. }
  91631. var scene = this._attachedCamera.getScene();
  91632. if (this._onPrePointerObservableObserver) {
  91633. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  91634. }
  91635. if (this._onAfterCheckInputsObserver) {
  91636. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  91637. }
  91638. if (this._onMeshTargetChangedObserver) {
  91639. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91640. }
  91641. this._attachedCamera = null;
  91642. };
  91643. /**
  91644. * Targets the given mesh and updates zoom level accordingly.
  91645. * @param mesh The mesh to target.
  91646. * @param radius Optional. If a cached radius position already exists, overrides default.
  91647. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91648. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91649. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91650. */
  91651. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  91652. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91653. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91654. mesh.computeWorldMatrix(true);
  91655. var boundingBox = mesh.getBoundingInfo().boundingBox;
  91656. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  91657. };
  91658. /**
  91659. * Targets the given mesh with its children and updates zoom level accordingly.
  91660. * @param mesh The mesh to target.
  91661. * @param radius Optional. If a cached radius position already exists, overrides default.
  91662. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91663. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91664. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91665. */
  91666. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  91667. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91668. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91669. mesh.computeWorldMatrix(true);
  91670. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  91671. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  91672. };
  91673. /**
  91674. * Targets the given meshes with their children and updates zoom level accordingly.
  91675. * @param meshes The mesh to target.
  91676. * @param radius Optional. If a cached radius position already exists, overrides default.
  91677. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91678. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91679. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91680. */
  91681. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  91682. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91683. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91684. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  91685. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  91686. for (var i = 0; i < meshes.length; i++) {
  91687. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  91688. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  91689. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  91690. }
  91691. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  91692. };
  91693. /**
  91694. * Targets the given mesh and updates zoom level accordingly.
  91695. * @param mesh The mesh to target.
  91696. * @param radius Optional. If a cached radius position already exists, overrides default.
  91697. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91698. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91699. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91700. */
  91701. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  91702. var _this = this;
  91703. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91704. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91705. var zoomTarget;
  91706. if (!this._attachedCamera) {
  91707. return;
  91708. }
  91709. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  91710. var bottom = minimumWorld.y;
  91711. var top = maximumWorld.y;
  91712. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  91713. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  91714. if (focusOnOriginXZ) {
  91715. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  91716. }
  91717. else {
  91718. var centerWorld = minimumWorld.add(radiusWorld);
  91719. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  91720. }
  91721. if (!this._vectorTransition) {
  91722. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  91723. }
  91724. this._betaIsAnimating = true;
  91725. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  91726. if (animatable) {
  91727. this._animatables.push(animatable);
  91728. }
  91729. // sets the radius and lower radius bounds
  91730. // Small delta ensures camera is not always at lower zoom limit.
  91731. var radius = 0;
  91732. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  91733. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  91734. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  91735. radius = position;
  91736. }
  91737. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  91738. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  91739. if (this._attachedCamera.lowerRadiusLimit === null) {
  91740. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  91741. }
  91742. }
  91743. // Set sensibilities
  91744. var extend = maximumWorld.subtract(minimumWorld).length();
  91745. this._attachedCamera.panningSensibility = 5000 / extend;
  91746. this._attachedCamera.wheelPrecision = 100 / radius;
  91747. // transition to new radius
  91748. if (!this._radiusTransition) {
  91749. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  91750. }
  91751. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  91752. _this.stopAllAnimations();
  91753. if (onAnimationEnd) {
  91754. onAnimationEnd();
  91755. }
  91756. if (_this._attachedCamera) {
  91757. _this._attachedCamera.storeState();
  91758. }
  91759. });
  91760. if (animatable) {
  91761. this._animatables.push(animatable);
  91762. }
  91763. };
  91764. /**
  91765. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  91766. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  91767. * frustum width.
  91768. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  91769. * to fully enclose the mesh in the viewing frustum.
  91770. */
  91771. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  91772. var size = maximumWorld.subtract(minimumWorld);
  91773. var boxVectorGlobalDiagonal = size.length();
  91774. var frustumSlope = this._getFrustumSlope();
  91775. // Formula for setting distance
  91776. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  91777. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  91778. // Horizon distance
  91779. var radius = radiusWithoutFraming * this._radiusScale;
  91780. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  91781. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  91782. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  91783. var camera = this._attachedCamera;
  91784. if (!camera) {
  91785. return 0;
  91786. }
  91787. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  91788. // Don't exceed the requested limit
  91789. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  91790. }
  91791. // Don't exceed the upper radius limit
  91792. if (camera.upperRadiusLimit) {
  91793. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  91794. }
  91795. return distance;
  91796. };
  91797. /**
  91798. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  91799. * is automatically returned to its default position (expected to be above ground plane).
  91800. */
  91801. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  91802. var _this = this;
  91803. if (this._elevationReturnTime < 0) {
  91804. return;
  91805. }
  91806. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  91807. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  91808. var limitBeta = Math.PI * 0.5;
  91809. // Bring the camera back up if below the ground plane
  91810. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  91811. this._betaIsAnimating = true;
  91812. //Transition to new position
  91813. this.stopAllAnimations();
  91814. if (!this._betaTransition) {
  91815. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  91816. }
  91817. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  91818. _this._clearAnimationLocks();
  91819. _this.stopAllAnimations();
  91820. });
  91821. if (animatabe) {
  91822. this._animatables.push(animatabe);
  91823. }
  91824. }
  91825. };
  91826. /**
  91827. * Returns the frustum slope based on the canvas ratio and camera FOV
  91828. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  91829. */
  91830. FramingBehavior.prototype._getFrustumSlope = function () {
  91831. // Calculate the viewport ratio
  91832. // Aspect Ratio is Height/Width.
  91833. var camera = this._attachedCamera;
  91834. if (!camera) {
  91835. return BABYLON.Vector2.Zero();
  91836. }
  91837. var engine = camera.getScene().getEngine();
  91838. var aspectRatio = engine.getAspectRatio(camera);
  91839. // Camera FOV is the vertical field of view (top-bottom) in radians.
  91840. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  91841. var frustumSlopeY = Math.tan(camera.fov / 2);
  91842. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  91843. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  91844. // along the forward vector.
  91845. var frustumSlopeX = frustumSlopeY * aspectRatio;
  91846. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  91847. };
  91848. /**
  91849. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  91850. */
  91851. FramingBehavior.prototype._clearAnimationLocks = function () {
  91852. this._betaIsAnimating = false;
  91853. };
  91854. /**
  91855. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  91856. */
  91857. FramingBehavior.prototype._applyUserInteraction = function () {
  91858. if (this.isUserIsMoving) {
  91859. this._lastInteractionTime = BABYLON.Tools.Now;
  91860. this.stopAllAnimations();
  91861. this._clearAnimationLocks();
  91862. }
  91863. };
  91864. /**
  91865. * Stops and removes all animations that have been applied to the camera
  91866. */
  91867. FramingBehavior.prototype.stopAllAnimations = function () {
  91868. if (this._attachedCamera) {
  91869. this._attachedCamera.animations = [];
  91870. }
  91871. while (this._animatables.length) {
  91872. if (this._animatables[0]) {
  91873. this._animatables[0].onAnimationEnd = null;
  91874. this._animatables[0].stop();
  91875. }
  91876. this._animatables.shift();
  91877. }
  91878. };
  91879. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  91880. /**
  91881. * Gets a value indicating if the user is moving the camera
  91882. */
  91883. get: function () {
  91884. if (!this._attachedCamera) {
  91885. return false;
  91886. }
  91887. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  91888. this._attachedCamera.inertialBetaOffset !== 0 ||
  91889. this._attachedCamera.inertialRadiusOffset !== 0 ||
  91890. this._attachedCamera.inertialPanningX !== 0 ||
  91891. this._attachedCamera.inertialPanningY !== 0 ||
  91892. this._isPointerDown;
  91893. },
  91894. enumerable: true,
  91895. configurable: true
  91896. });
  91897. /**
  91898. * The easing function used by animations
  91899. */
  91900. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  91901. /**
  91902. * The easing mode used by animations
  91903. */
  91904. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  91905. // Statics
  91906. /**
  91907. * The camera can move all the way towards the mesh.
  91908. */
  91909. FramingBehavior.IgnoreBoundsSizeMode = 0;
  91910. /**
  91911. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  91912. */
  91913. FramingBehavior.FitFrustumSidesMode = 1;
  91914. return FramingBehavior;
  91915. }());
  91916. BABYLON.FramingBehavior = FramingBehavior;
  91917. })(BABYLON || (BABYLON = {}));
  91918. //# sourceMappingURL=babylon.framingBehavior.js.map
  91919. "use strict";
  91920. var BABYLON;
  91921. (function (BABYLON) {
  91922. /**
  91923. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  91924. */
  91925. var BouncingBehavior = /** @class */ (function () {
  91926. function BouncingBehavior() {
  91927. /**
  91928. * The duration of the animation, in milliseconds
  91929. */
  91930. this.transitionDuration = 450;
  91931. /**
  91932. * Length of the distance animated by the transition when lower radius is reached
  91933. */
  91934. this.lowerRadiusTransitionRange = 2;
  91935. /**
  91936. * Length of the distance animated by the transition when upper radius is reached
  91937. */
  91938. this.upperRadiusTransitionRange = -2;
  91939. this._autoTransitionRange = false;
  91940. // Animations
  91941. this._radiusIsAnimating = false;
  91942. this._radiusBounceTransition = null;
  91943. this._animatables = new Array();
  91944. }
  91945. Object.defineProperty(BouncingBehavior.prototype, "name", {
  91946. get: function () {
  91947. return "Bouncing";
  91948. },
  91949. enumerable: true,
  91950. configurable: true
  91951. });
  91952. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  91953. /**
  91954. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  91955. */
  91956. get: function () {
  91957. return this._autoTransitionRange;
  91958. },
  91959. /**
  91960. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  91961. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  91962. */
  91963. set: function (value) {
  91964. var _this = this;
  91965. if (this._autoTransitionRange === value) {
  91966. return;
  91967. }
  91968. this._autoTransitionRange = value;
  91969. var camera = this._attachedCamera;
  91970. if (!camera) {
  91971. return;
  91972. }
  91973. if (value) {
  91974. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  91975. if (!mesh) {
  91976. return;
  91977. }
  91978. mesh.computeWorldMatrix(true);
  91979. var diagonal = mesh.getBoundingInfo().diagonalLength;
  91980. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  91981. _this.upperRadiusTransitionRange = diagonal * 0.05;
  91982. });
  91983. }
  91984. else if (this._onMeshTargetChangedObserver) {
  91985. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91986. }
  91987. },
  91988. enumerable: true,
  91989. configurable: true
  91990. });
  91991. BouncingBehavior.prototype.init = function () {
  91992. // Do notihng
  91993. };
  91994. BouncingBehavior.prototype.attach = function (camera) {
  91995. var _this = this;
  91996. this._attachedCamera = camera;
  91997. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  91998. if (!_this._attachedCamera) {
  91999. return;
  92000. }
  92001. // Add the bounce animation to the lower radius limit
  92002. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  92003. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  92004. }
  92005. // Add the bounce animation to the upper radius limit
  92006. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  92007. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  92008. }
  92009. });
  92010. };
  92011. BouncingBehavior.prototype.detach = function () {
  92012. if (!this._attachedCamera) {
  92013. return;
  92014. }
  92015. if (this._onAfterCheckInputsObserver) {
  92016. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92017. }
  92018. if (this._onMeshTargetChangedObserver) {
  92019. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92020. }
  92021. this._attachedCamera = null;
  92022. };
  92023. /**
  92024. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  92025. * @param radiusLimit The limit to check against.
  92026. * @return Bool to indicate if at limit.
  92027. */
  92028. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  92029. if (!this._attachedCamera) {
  92030. return false;
  92031. }
  92032. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  92033. return true;
  92034. }
  92035. return false;
  92036. };
  92037. /**
  92038. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  92039. * @param radiusDelta The delta by which to animate to. Can be negative.
  92040. */
  92041. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  92042. var _this = this;
  92043. if (!this._attachedCamera) {
  92044. return;
  92045. }
  92046. if (!this._radiusBounceTransition) {
  92047. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  92048. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  92049. }
  92050. // Prevent zoom until bounce has completed
  92051. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  92052. this._attachedCamera.wheelPrecision = Infinity;
  92053. this._attachedCamera.inertialRadiusOffset = 0;
  92054. // Animate to the radius limit
  92055. this.stopAllAnimations();
  92056. this._radiusIsAnimating = true;
  92057. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  92058. if (animatable) {
  92059. this._animatables.push(animatable);
  92060. }
  92061. };
  92062. /**
  92063. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  92064. */
  92065. BouncingBehavior.prototype._clearAnimationLocks = function () {
  92066. this._radiusIsAnimating = false;
  92067. if (this._attachedCamera) {
  92068. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  92069. }
  92070. };
  92071. /**
  92072. * Stops and removes all animations that have been applied to the camera
  92073. */
  92074. BouncingBehavior.prototype.stopAllAnimations = function () {
  92075. if (this._attachedCamera) {
  92076. this._attachedCamera.animations = [];
  92077. }
  92078. while (this._animatables.length) {
  92079. this._animatables[0].onAnimationEnd = null;
  92080. this._animatables[0].stop();
  92081. this._animatables.shift();
  92082. }
  92083. };
  92084. /**
  92085. * The easing function used by animations
  92086. */
  92087. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  92088. /**
  92089. * The easing mode used by animations
  92090. */
  92091. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  92092. return BouncingBehavior;
  92093. }());
  92094. BABYLON.BouncingBehavior = BouncingBehavior;
  92095. })(BABYLON || (BABYLON = {}));
  92096. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  92097. "use strict";
  92098. var BABYLON;
  92099. (function (BABYLON) {
  92100. var AutoRotationBehavior = /** @class */ (function () {
  92101. function AutoRotationBehavior() {
  92102. this._zoomStopsAnimation = false;
  92103. this._idleRotationSpeed = 0.05;
  92104. this._idleRotationWaitTime = 2000;
  92105. this._idleRotationSpinupTime = 2000;
  92106. this._isPointerDown = false;
  92107. this._lastFrameTime = null;
  92108. this._lastInteractionTime = -Infinity;
  92109. this._cameraRotationSpeed = 0;
  92110. this._lastFrameRadius = 0;
  92111. }
  92112. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  92113. get: function () {
  92114. return "AutoRotation";
  92115. },
  92116. enumerable: true,
  92117. configurable: true
  92118. });
  92119. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  92120. /**
  92121. * Gets the flag that indicates if user zooming should stop animation.
  92122. */
  92123. get: function () {
  92124. return this._zoomStopsAnimation;
  92125. },
  92126. /**
  92127. * Sets the flag that indicates if user zooming should stop animation.
  92128. */
  92129. set: function (flag) {
  92130. this._zoomStopsAnimation = flag;
  92131. },
  92132. enumerable: true,
  92133. configurable: true
  92134. });
  92135. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  92136. /**
  92137. * Gets the default speed at which the camera rotates around the model.
  92138. */
  92139. get: function () {
  92140. return this._idleRotationSpeed;
  92141. },
  92142. /**
  92143. * Sets the default speed at which the camera rotates around the model.
  92144. */
  92145. set: function (speed) {
  92146. this._idleRotationSpeed = speed;
  92147. },
  92148. enumerable: true,
  92149. configurable: true
  92150. });
  92151. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  92152. /**
  92153. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  92154. */
  92155. get: function () {
  92156. return this._idleRotationWaitTime;
  92157. },
  92158. /**
  92159. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  92160. */
  92161. set: function (time) {
  92162. this._idleRotationWaitTime = time;
  92163. },
  92164. enumerable: true,
  92165. configurable: true
  92166. });
  92167. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  92168. /**
  92169. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92170. */
  92171. get: function () {
  92172. return this._idleRotationSpinupTime;
  92173. },
  92174. /**
  92175. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92176. */
  92177. set: function (time) {
  92178. this._idleRotationSpinupTime = time;
  92179. },
  92180. enumerable: true,
  92181. configurable: true
  92182. });
  92183. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  92184. /**
  92185. * Gets a value indicating if the camera is currently rotating because of this behavior
  92186. */
  92187. get: function () {
  92188. return Math.abs(this._cameraRotationSpeed) > 0;
  92189. },
  92190. enumerable: true,
  92191. configurable: true
  92192. });
  92193. AutoRotationBehavior.prototype.init = function () {
  92194. // Do notihng
  92195. };
  92196. AutoRotationBehavior.prototype.attach = function (camera) {
  92197. var _this = this;
  92198. this._attachedCamera = camera;
  92199. var scene = this._attachedCamera.getScene();
  92200. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92201. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92202. _this._isPointerDown = true;
  92203. return;
  92204. }
  92205. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92206. _this._isPointerDown = false;
  92207. }
  92208. });
  92209. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92210. var now = BABYLON.Tools.Now;
  92211. var dt = 0;
  92212. if (_this._lastFrameTime != null) {
  92213. dt = now - _this._lastFrameTime;
  92214. }
  92215. _this._lastFrameTime = now;
  92216. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92217. _this._applyUserInteraction();
  92218. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  92219. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  92220. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  92221. // Step camera rotation by rotation speed
  92222. if (_this._attachedCamera) {
  92223. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  92224. }
  92225. });
  92226. };
  92227. AutoRotationBehavior.prototype.detach = function () {
  92228. if (!this._attachedCamera) {
  92229. return;
  92230. }
  92231. var scene = this._attachedCamera.getScene();
  92232. if (this._onPrePointerObservableObserver) {
  92233. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92234. }
  92235. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92236. this._attachedCamera = null;
  92237. };
  92238. /**
  92239. * Returns true if user is scrolling.
  92240. * @return true if user is scrolling.
  92241. */
  92242. AutoRotationBehavior.prototype._userIsZooming = function () {
  92243. if (!this._attachedCamera) {
  92244. return false;
  92245. }
  92246. return this._attachedCamera.inertialRadiusOffset !== 0;
  92247. };
  92248. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  92249. if (!this._attachedCamera) {
  92250. return false;
  92251. }
  92252. var zoomHasHitLimit = false;
  92253. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  92254. zoomHasHitLimit = true;
  92255. }
  92256. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  92257. this._lastFrameRadius = this._attachedCamera.radius;
  92258. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  92259. };
  92260. /**
  92261. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92262. */
  92263. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  92264. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  92265. this._lastInteractionTime = BABYLON.Tools.Now;
  92266. }
  92267. };
  92268. // Tools
  92269. AutoRotationBehavior.prototype._userIsMoving = function () {
  92270. if (!this._attachedCamera) {
  92271. return false;
  92272. }
  92273. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92274. this._attachedCamera.inertialBetaOffset !== 0 ||
  92275. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92276. this._attachedCamera.inertialPanningX !== 0 ||
  92277. this._attachedCamera.inertialPanningY !== 0 ||
  92278. this._isPointerDown;
  92279. };
  92280. return AutoRotationBehavior;
  92281. }());
  92282. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  92283. })(BABYLON || (BABYLON = {}));
  92284. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  92285. "use strict";
  92286. var BABYLON;
  92287. (function (BABYLON) {
  92288. var NullEngineOptions = /** @class */ (function () {
  92289. function NullEngineOptions() {
  92290. this.renderWidth = 512;
  92291. this.renderHeight = 256;
  92292. this.textureSize = 512;
  92293. this.deterministicLockstep = false;
  92294. this.lockstepMaxSteps = 4;
  92295. }
  92296. return NullEngineOptions;
  92297. }());
  92298. BABYLON.NullEngineOptions = NullEngineOptions;
  92299. /**
  92300. * The null engine class provides support for headless version of babylon.js.
  92301. * This can be used in server side scenario or for testing purposes
  92302. */
  92303. var NullEngine = /** @class */ (function (_super) {
  92304. __extends(NullEngine, _super);
  92305. function NullEngine(options) {
  92306. if (options === void 0) { options = new NullEngineOptions(); }
  92307. var _this = _super.call(this, null) || this;
  92308. if (options.deterministicLockstep === undefined) {
  92309. options.deterministicLockstep = false;
  92310. }
  92311. if (options.lockstepMaxSteps === undefined) {
  92312. options.lockstepMaxSteps = 4;
  92313. }
  92314. _this._options = options;
  92315. // Init caps
  92316. // We consider we are on a webgl1 capable device
  92317. _this._caps = new BABYLON.EngineCapabilities();
  92318. _this._caps.maxTexturesImageUnits = 16;
  92319. _this._caps.maxVertexTextureImageUnits = 16;
  92320. _this._caps.maxTextureSize = 512;
  92321. _this._caps.maxCubemapTextureSize = 512;
  92322. _this._caps.maxRenderTextureSize = 512;
  92323. _this._caps.maxVertexAttribs = 16;
  92324. _this._caps.maxVaryingVectors = 16;
  92325. _this._caps.maxFragmentUniformVectors = 16;
  92326. _this._caps.maxVertexUniformVectors = 16;
  92327. // Extensions
  92328. _this._caps.standardDerivatives = false;
  92329. _this._caps.astc = null;
  92330. _this._caps.s3tc = null;
  92331. _this._caps.pvrtc = null;
  92332. _this._caps.etc1 = null;
  92333. _this._caps.etc2 = null;
  92334. _this._caps.textureAnisotropicFilterExtension = null;
  92335. _this._caps.maxAnisotropy = 0;
  92336. _this._caps.uintIndices = false;
  92337. _this._caps.fragmentDepthSupported = false;
  92338. _this._caps.highPrecisionShaderSupported = true;
  92339. _this._caps.colorBufferFloat = false;
  92340. _this._caps.textureFloat = false;
  92341. _this._caps.textureFloatLinearFiltering = false;
  92342. _this._caps.textureFloatRender = false;
  92343. _this._caps.textureHalfFloat = false;
  92344. _this._caps.textureHalfFloatLinearFiltering = false;
  92345. _this._caps.textureHalfFloatRender = false;
  92346. _this._caps.textureLOD = false;
  92347. _this._caps.drawBuffersExtension = false;
  92348. _this._caps.depthTextureExtension = false;
  92349. _this._caps.vertexArrayObject = false;
  92350. _this._caps.instancedArrays = false;
  92351. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  92352. // Wrappers
  92353. if (typeof URL === "undefined") {
  92354. URL = {
  92355. createObjectURL: function () { },
  92356. revokeObjectURL: function () { }
  92357. };
  92358. }
  92359. if (typeof Blob === "undefined") {
  92360. Blob = function () { };
  92361. }
  92362. return _this;
  92363. }
  92364. NullEngine.prototype.isDeterministicLockStep = function () {
  92365. return this._options.deterministicLockstep;
  92366. };
  92367. NullEngine.prototype.getLockstepMaxSteps = function () {
  92368. return this._options.lockstepMaxSteps;
  92369. };
  92370. NullEngine.prototype.getHardwareScalingLevel = function () {
  92371. return 1.0;
  92372. };
  92373. NullEngine.prototype.createVertexBuffer = function (vertices) {
  92374. return {
  92375. capacity: 0,
  92376. references: 1,
  92377. is32Bits: false
  92378. };
  92379. };
  92380. NullEngine.prototype.createIndexBuffer = function (indices) {
  92381. return {
  92382. capacity: 0,
  92383. references: 1,
  92384. is32Bits: false
  92385. };
  92386. };
  92387. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  92388. if (stencil === void 0) { stencil = false; }
  92389. };
  92390. NullEngine.prototype.getRenderWidth = function (useScreen) {
  92391. if (useScreen === void 0) { useScreen = false; }
  92392. if (!useScreen && this._currentRenderTarget) {
  92393. return this._currentRenderTarget.width;
  92394. }
  92395. return this._options.renderWidth;
  92396. };
  92397. NullEngine.prototype.getRenderHeight = function (useScreen) {
  92398. if (useScreen === void 0) { useScreen = false; }
  92399. if (!useScreen && this._currentRenderTarget) {
  92400. return this._currentRenderTarget.height;
  92401. }
  92402. return this._options.renderHeight;
  92403. };
  92404. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  92405. this._cachedViewport = viewport;
  92406. };
  92407. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  92408. return {
  92409. transformFeedback: null,
  92410. __SPECTOR_rebuildProgram: null
  92411. };
  92412. };
  92413. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  92414. return [];
  92415. };
  92416. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  92417. return [];
  92418. };
  92419. NullEngine.prototype.bindSamplers = function (effect) {
  92420. this._currentEffect = null;
  92421. };
  92422. NullEngine.prototype.enableEffect = function (effect) {
  92423. this._currentEffect = effect;
  92424. if (effect.onBind) {
  92425. effect.onBind(effect);
  92426. }
  92427. effect.onBindObservable.notifyObservers(effect);
  92428. };
  92429. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  92430. if (zOffset === void 0) { zOffset = 0; }
  92431. if (reverseSide === void 0) { reverseSide = false; }
  92432. };
  92433. NullEngine.prototype.setIntArray = function (uniform, array) {
  92434. };
  92435. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  92436. };
  92437. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  92438. };
  92439. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  92440. };
  92441. NullEngine.prototype.setFloatArray = function (uniform, array) {
  92442. };
  92443. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  92444. };
  92445. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  92446. };
  92447. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  92448. };
  92449. NullEngine.prototype.setArray = function (uniform, array) {
  92450. };
  92451. NullEngine.prototype.setArray2 = function (uniform, array) {
  92452. };
  92453. NullEngine.prototype.setArray3 = function (uniform, array) {
  92454. };
  92455. NullEngine.prototype.setArray4 = function (uniform, array) {
  92456. };
  92457. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  92458. };
  92459. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  92460. };
  92461. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  92462. };
  92463. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  92464. };
  92465. NullEngine.prototype.setFloat = function (uniform, value) {
  92466. };
  92467. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  92468. };
  92469. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  92470. };
  92471. NullEngine.prototype.setBool = function (uniform, bool) {
  92472. };
  92473. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  92474. };
  92475. NullEngine.prototype.setColor3 = function (uniform, color3) {
  92476. };
  92477. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  92478. };
  92479. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  92480. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  92481. if (this._alphaMode === mode) {
  92482. return;
  92483. }
  92484. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  92485. if (!noDepthWriteChange) {
  92486. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  92487. }
  92488. this._alphaMode = mode;
  92489. };
  92490. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  92491. };
  92492. NullEngine.prototype.wipeCaches = function (bruteForce) {
  92493. if (this.preventCacheWipeBetweenFrames) {
  92494. return;
  92495. }
  92496. this.resetTextureCache();
  92497. this._currentEffect = null;
  92498. if (bruteForce) {
  92499. this._currentProgram = null;
  92500. this._stencilState.reset();
  92501. this._depthCullingState.reset();
  92502. this._alphaState.reset();
  92503. }
  92504. this._cachedVertexBuffers = null;
  92505. this._cachedIndexBuffer = null;
  92506. this._cachedEffectForVertexBuffers = null;
  92507. };
  92508. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  92509. };
  92510. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  92511. };
  92512. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  92513. };
  92514. NullEngine.prototype._createTexture = function () {
  92515. return {};
  92516. };
  92517. NullEngine.prototype._releaseTexture = function (texture) {
  92518. };
  92519. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  92520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92521. if (onLoad === void 0) { onLoad = null; }
  92522. if (onError === void 0) { onError = null; }
  92523. if (buffer === void 0) { buffer = null; }
  92524. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  92525. var url = String(urlArg);
  92526. texture.url = url;
  92527. texture.generateMipMaps = !noMipmap;
  92528. texture.samplingMode = samplingMode;
  92529. texture.invertY = invertY;
  92530. texture.baseWidth = this._options.textureSize;
  92531. texture.baseHeight = this._options.textureSize;
  92532. texture.width = this._options.textureSize;
  92533. texture.height = this._options.textureSize;
  92534. if (format) {
  92535. texture.format = format;
  92536. }
  92537. texture.isReady = true;
  92538. if (onLoad) {
  92539. onLoad();
  92540. }
  92541. return texture;
  92542. };
  92543. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  92544. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  92545. if (options !== undefined && typeof options === "object") {
  92546. fullOptions.generateMipMaps = options.generateMipMaps;
  92547. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  92548. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  92549. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  92550. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  92551. }
  92552. else {
  92553. fullOptions.generateMipMaps = options;
  92554. fullOptions.generateDepthBuffer = true;
  92555. fullOptions.generateStencilBuffer = false;
  92556. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92557. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92558. }
  92559. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  92560. var width = size.width || size;
  92561. var height = size.height || size;
  92562. texture._depthStencilBuffer = {};
  92563. texture._framebuffer = {};
  92564. texture.baseWidth = width;
  92565. texture.baseHeight = height;
  92566. texture.width = width;
  92567. texture.height = height;
  92568. texture.isReady = true;
  92569. texture.samples = 1;
  92570. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  92571. texture.samplingMode = fullOptions.samplingMode;
  92572. texture.type = fullOptions.type;
  92573. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  92574. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  92575. return texture;
  92576. };
  92577. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  92578. texture.samplingMode = samplingMode;
  92579. };
  92580. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  92581. if (this._currentRenderTarget) {
  92582. this.unBindFramebuffer(this._currentRenderTarget);
  92583. }
  92584. this._currentRenderTarget = texture;
  92585. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  92586. if (this._cachedViewport && !forceFullscreenViewport) {
  92587. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  92588. }
  92589. };
  92590. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  92591. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  92592. this._currentRenderTarget = null;
  92593. if (onBeforeUnbind) {
  92594. if (texture._MSAAFramebuffer) {
  92595. this._currentFramebuffer = texture._framebuffer;
  92596. }
  92597. onBeforeUnbind();
  92598. }
  92599. this._currentFramebuffer = null;
  92600. };
  92601. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  92602. var vbo = {
  92603. capacity: 1,
  92604. references: 1,
  92605. is32Bits: false
  92606. };
  92607. return vbo;
  92608. };
  92609. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  92610. if (offset === void 0) { offset = 0; }
  92611. };
  92612. /**
  92613. * Updates a dynamic vertex buffer.
  92614. * @param vertexBuffer the vertex buffer to update
  92615. * @param data the data used to update the vertex buffer
  92616. * @param byteOffset the byte offset of the data (optional)
  92617. * @param byteLength the byte length of the data (optional)
  92618. */
  92619. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  92620. };
  92621. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  92622. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  92623. this._boundTexturesCache[this._activeChannel] = texture;
  92624. }
  92625. };
  92626. NullEngine.prototype._bindTexture = function (channel, texture) {
  92627. if (channel < 0) {
  92628. return;
  92629. }
  92630. this._bindTextureDirectly(0, texture);
  92631. };
  92632. NullEngine.prototype._releaseBuffer = function (buffer) {
  92633. buffer.references--;
  92634. if (buffer.references === 0) {
  92635. return true;
  92636. }
  92637. return false;
  92638. };
  92639. return NullEngine;
  92640. }(BABYLON.Engine));
  92641. BABYLON.NullEngine = NullEngine;
  92642. })(BABYLON || (BABYLON = {}));
  92643. //# sourceMappingURL=babylon.nullEngine.js.map
  92644. "use strict";
  92645. var BABYLON;
  92646. (function (BABYLON) {
  92647. /**
  92648. * This class can be used to get instrumentation data from a Babylon engine
  92649. */
  92650. var EngineInstrumentation = /** @class */ (function () {
  92651. function EngineInstrumentation(engine) {
  92652. this.engine = engine;
  92653. this._captureGPUFrameTime = false;
  92654. this._gpuFrameTime = new BABYLON.PerfCounter();
  92655. this._captureShaderCompilationTime = false;
  92656. this._shaderCompilationTime = new BABYLON.PerfCounter();
  92657. // Observers
  92658. this._onBeginFrameObserver = null;
  92659. this._onEndFrameObserver = null;
  92660. this._onBeforeShaderCompilationObserver = null;
  92661. this._onAfterShaderCompilationObserver = null;
  92662. }
  92663. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  92664. // Properties
  92665. /**
  92666. * Gets the perf counter used for GPU frame time
  92667. */
  92668. get: function () {
  92669. return this._gpuFrameTime;
  92670. },
  92671. enumerable: true,
  92672. configurable: true
  92673. });
  92674. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  92675. /**
  92676. * Gets the GPU frame time capture status
  92677. */
  92678. get: function () {
  92679. return this._captureGPUFrameTime;
  92680. },
  92681. /**
  92682. * Enable or disable the GPU frame time capture
  92683. */
  92684. set: function (value) {
  92685. var _this = this;
  92686. if (value === this._captureGPUFrameTime) {
  92687. return;
  92688. }
  92689. this._captureGPUFrameTime = value;
  92690. if (value) {
  92691. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  92692. if (!_this._gpuFrameTimeToken) {
  92693. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  92694. }
  92695. });
  92696. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  92697. if (!_this._gpuFrameTimeToken) {
  92698. return;
  92699. }
  92700. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  92701. if (time > -1) {
  92702. _this._gpuFrameTimeToken = null;
  92703. _this._gpuFrameTime.fetchNewFrame();
  92704. _this._gpuFrameTime.addCount(time, true);
  92705. }
  92706. });
  92707. }
  92708. else {
  92709. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  92710. this._onBeginFrameObserver = null;
  92711. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  92712. this._onEndFrameObserver = null;
  92713. }
  92714. },
  92715. enumerable: true,
  92716. configurable: true
  92717. });
  92718. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  92719. /**
  92720. * Gets the perf counter used for shader compilation time
  92721. */
  92722. get: function () {
  92723. return this._shaderCompilationTime;
  92724. },
  92725. enumerable: true,
  92726. configurable: true
  92727. });
  92728. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  92729. /**
  92730. * Gets the shader compilation time capture status
  92731. */
  92732. get: function () {
  92733. return this._captureShaderCompilationTime;
  92734. },
  92735. /**
  92736. * Enable or disable the shader compilation time capture
  92737. */
  92738. set: function (value) {
  92739. var _this = this;
  92740. if (value === this._captureShaderCompilationTime) {
  92741. return;
  92742. }
  92743. this._captureShaderCompilationTime = value;
  92744. if (value) {
  92745. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  92746. _this._shaderCompilationTime.fetchNewFrame();
  92747. _this._shaderCompilationTime.beginMonitoring();
  92748. });
  92749. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  92750. _this._shaderCompilationTime.endMonitoring();
  92751. });
  92752. }
  92753. else {
  92754. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  92755. this._onBeforeShaderCompilationObserver = null;
  92756. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  92757. this._onAfterShaderCompilationObserver = null;
  92758. }
  92759. },
  92760. enumerable: true,
  92761. configurable: true
  92762. });
  92763. EngineInstrumentation.prototype.dispose = function () {
  92764. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  92765. this._onBeginFrameObserver = null;
  92766. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  92767. this._onEndFrameObserver = null;
  92768. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  92769. this._onBeforeShaderCompilationObserver = null;
  92770. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  92771. this._onAfterShaderCompilationObserver = null;
  92772. this.engine = null;
  92773. };
  92774. return EngineInstrumentation;
  92775. }());
  92776. BABYLON.EngineInstrumentation = EngineInstrumentation;
  92777. })(BABYLON || (BABYLON = {}));
  92778. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  92779. "use strict";
  92780. var BABYLON;
  92781. (function (BABYLON) {
  92782. /**
  92783. * This class can be used to get instrumentation data from a Babylon engine
  92784. */
  92785. var SceneInstrumentation = /** @class */ (function () {
  92786. function SceneInstrumentation(scene) {
  92787. var _this = this;
  92788. this.scene = scene;
  92789. this._captureActiveMeshesEvaluationTime = false;
  92790. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  92791. this._captureRenderTargetsRenderTime = false;
  92792. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  92793. this._captureFrameTime = false;
  92794. this._frameTime = new BABYLON.PerfCounter();
  92795. this._captureRenderTime = false;
  92796. this._renderTime = new BABYLON.PerfCounter();
  92797. this._captureInterFrameTime = false;
  92798. this._interFrameTime = new BABYLON.PerfCounter();
  92799. this._captureParticlesRenderTime = false;
  92800. this._particlesRenderTime = new BABYLON.PerfCounter();
  92801. this._captureSpritesRenderTime = false;
  92802. this._spritesRenderTime = new BABYLON.PerfCounter();
  92803. this._capturePhysicsTime = false;
  92804. this._physicsTime = new BABYLON.PerfCounter();
  92805. this._captureAnimationsTime = false;
  92806. this._animationsTime = new BABYLON.PerfCounter();
  92807. // Observers
  92808. this._onBeforeActiveMeshesEvaluationObserver = null;
  92809. this._onAfterActiveMeshesEvaluationObserver = null;
  92810. this._onBeforeRenderTargetsRenderObserver = null;
  92811. this._onAfterRenderTargetsRenderObserver = null;
  92812. this._onAfterRenderObserver = null;
  92813. this._onBeforeDrawPhaseObserver = null;
  92814. this._onAfterDrawPhaseObserver = null;
  92815. this._onBeforeAnimationsObserver = null;
  92816. this._onBeforeParticlesRenderingObserver = null;
  92817. this._onAfterParticlesRenderingObserver = null;
  92818. this._onBeforeSpritesRenderingObserver = null;
  92819. this._onAfterSpritesRenderingObserver = null;
  92820. this._onBeforePhysicsObserver = null;
  92821. this._onAfterPhysicsObserver = null;
  92822. this._onAfterAnimationsObserver = null;
  92823. // Before render
  92824. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  92825. if (_this._captureActiveMeshesEvaluationTime) {
  92826. _this._activeMeshesEvaluationTime.fetchNewFrame();
  92827. }
  92828. if (_this._captureRenderTargetsRenderTime) {
  92829. _this._renderTargetsRenderTime.fetchNewFrame();
  92830. }
  92831. if (_this._captureFrameTime) {
  92832. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  92833. _this._frameTime.beginMonitoring();
  92834. }
  92835. if (_this._captureInterFrameTime) {
  92836. _this._interFrameTime.endMonitoring();
  92837. }
  92838. if (_this._captureParticlesRenderTime) {
  92839. _this._particlesRenderTime.fetchNewFrame();
  92840. }
  92841. if (_this._captureSpritesRenderTime) {
  92842. _this._spritesRenderTime.fetchNewFrame();
  92843. }
  92844. if (_this._captureAnimationsTime) {
  92845. _this._animationsTime.beginMonitoring();
  92846. }
  92847. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  92848. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  92849. });
  92850. // After render
  92851. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  92852. if (_this._captureFrameTime) {
  92853. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  92854. _this._frameTime.endMonitoring();
  92855. }
  92856. if (_this._captureRenderTime) {
  92857. _this._renderTime.endMonitoring(false);
  92858. }
  92859. if (_this._captureInterFrameTime) {
  92860. _this._interFrameTime.beginMonitoring();
  92861. }
  92862. });
  92863. }
  92864. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  92865. // Properties
  92866. /**
  92867. * Gets the perf counter used for active meshes evaluation time
  92868. */
  92869. get: function () {
  92870. return this._activeMeshesEvaluationTime;
  92871. },
  92872. enumerable: true,
  92873. configurable: true
  92874. });
  92875. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  92876. /**
  92877. * Gets the active meshes evaluation time capture status
  92878. */
  92879. get: function () {
  92880. return this._captureActiveMeshesEvaluationTime;
  92881. },
  92882. /**
  92883. * Enable or disable the active meshes evaluation time capture
  92884. */
  92885. set: function (value) {
  92886. var _this = this;
  92887. if (value === this._captureActiveMeshesEvaluationTime) {
  92888. return;
  92889. }
  92890. this._captureActiveMeshesEvaluationTime = value;
  92891. if (value) {
  92892. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  92893. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  92894. _this._activeMeshesEvaluationTime.beginMonitoring();
  92895. });
  92896. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  92897. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  92898. _this._activeMeshesEvaluationTime.endMonitoring();
  92899. });
  92900. }
  92901. else {
  92902. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  92903. this._onBeforeActiveMeshesEvaluationObserver = null;
  92904. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  92905. this._onAfterActiveMeshesEvaluationObserver = null;
  92906. }
  92907. },
  92908. enumerable: true,
  92909. configurable: true
  92910. });
  92911. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  92912. /**
  92913. * Gets the perf counter used for render targets render time
  92914. */
  92915. get: function () {
  92916. return this._renderTargetsRenderTime;
  92917. },
  92918. enumerable: true,
  92919. configurable: true
  92920. });
  92921. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  92922. /**
  92923. * Gets the render targets render time capture status
  92924. */
  92925. get: function () {
  92926. return this._captureRenderTargetsRenderTime;
  92927. },
  92928. /**
  92929. * Enable or disable the render targets render time capture
  92930. */
  92931. set: function (value) {
  92932. var _this = this;
  92933. if (value === this._captureRenderTargetsRenderTime) {
  92934. return;
  92935. }
  92936. this._captureRenderTargetsRenderTime = value;
  92937. if (value) {
  92938. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  92939. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  92940. _this._renderTargetsRenderTime.beginMonitoring();
  92941. });
  92942. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  92943. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  92944. _this._renderTargetsRenderTime.endMonitoring(false);
  92945. });
  92946. }
  92947. else {
  92948. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  92949. this._onBeforeRenderTargetsRenderObserver = null;
  92950. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  92951. this._onAfterRenderTargetsRenderObserver = null;
  92952. }
  92953. },
  92954. enumerable: true,
  92955. configurable: true
  92956. });
  92957. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  92958. /**
  92959. * Gets the perf counter used for particles render time
  92960. */
  92961. get: function () {
  92962. return this._particlesRenderTime;
  92963. },
  92964. enumerable: true,
  92965. configurable: true
  92966. });
  92967. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  92968. /**
  92969. * Gets the particles render time capture status
  92970. */
  92971. get: function () {
  92972. return this._captureParticlesRenderTime;
  92973. },
  92974. /**
  92975. * Enable or disable the particles render time capture
  92976. */
  92977. set: function (value) {
  92978. var _this = this;
  92979. if (value === this._captureParticlesRenderTime) {
  92980. return;
  92981. }
  92982. this._captureParticlesRenderTime = value;
  92983. if (value) {
  92984. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  92985. BABYLON.Tools.StartPerformanceCounter("Particles");
  92986. _this._particlesRenderTime.beginMonitoring();
  92987. });
  92988. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  92989. BABYLON.Tools.EndPerformanceCounter("Particles");
  92990. _this._particlesRenderTime.endMonitoring(false);
  92991. });
  92992. }
  92993. else {
  92994. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  92995. this._onBeforeParticlesRenderingObserver = null;
  92996. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  92997. this._onAfterParticlesRenderingObserver = null;
  92998. }
  92999. },
  93000. enumerable: true,
  93001. configurable: true
  93002. });
  93003. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  93004. /**
  93005. * Gets the perf counter used for sprites render time
  93006. */
  93007. get: function () {
  93008. return this._spritesRenderTime;
  93009. },
  93010. enumerable: true,
  93011. configurable: true
  93012. });
  93013. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  93014. /**
  93015. * Gets the sprites render time capture status
  93016. */
  93017. get: function () {
  93018. return this._captureSpritesRenderTime;
  93019. },
  93020. /**
  93021. * Enable or disable the sprites render time capture
  93022. */
  93023. set: function (value) {
  93024. var _this = this;
  93025. if (value === this._captureSpritesRenderTime) {
  93026. return;
  93027. }
  93028. this._captureSpritesRenderTime = value;
  93029. if (value) {
  93030. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  93031. BABYLON.Tools.StartPerformanceCounter("Sprites");
  93032. _this._spritesRenderTime.beginMonitoring();
  93033. });
  93034. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  93035. BABYLON.Tools.EndPerformanceCounter("Sprites");
  93036. _this._spritesRenderTime.endMonitoring(false);
  93037. });
  93038. }
  93039. else {
  93040. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93041. this._onBeforeSpritesRenderingObserver = null;
  93042. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93043. this._onAfterSpritesRenderingObserver = null;
  93044. }
  93045. },
  93046. enumerable: true,
  93047. configurable: true
  93048. });
  93049. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  93050. /**
  93051. * Gets the perf counter used for physics time
  93052. */
  93053. get: function () {
  93054. return this._physicsTime;
  93055. },
  93056. enumerable: true,
  93057. configurable: true
  93058. });
  93059. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  93060. /**
  93061. * Gets the physics time capture status
  93062. */
  93063. get: function () {
  93064. return this._capturePhysicsTime;
  93065. },
  93066. /**
  93067. * Enable or disable the physics time capture
  93068. */
  93069. set: function (value) {
  93070. var _this = this;
  93071. if (value === this._capturePhysicsTime) {
  93072. return;
  93073. }
  93074. this._capturePhysicsTime = value;
  93075. if (value) {
  93076. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  93077. BABYLON.Tools.StartPerformanceCounter("Physics");
  93078. _this._physicsTime.beginMonitoring();
  93079. });
  93080. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  93081. BABYLON.Tools.EndPerformanceCounter("Physics");
  93082. _this._physicsTime.endMonitoring();
  93083. });
  93084. }
  93085. else {
  93086. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93087. this._onBeforePhysicsObserver = null;
  93088. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93089. this._onAfterPhysicsObserver = null;
  93090. }
  93091. },
  93092. enumerable: true,
  93093. configurable: true
  93094. });
  93095. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  93096. /**
  93097. * Gets the perf counter used for animations time
  93098. */
  93099. get: function () {
  93100. return this._animationsTime;
  93101. },
  93102. enumerable: true,
  93103. configurable: true
  93104. });
  93105. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  93106. /**
  93107. * Gets the animations time capture status
  93108. */
  93109. get: function () {
  93110. return this._captureAnimationsTime;
  93111. },
  93112. /**
  93113. * Enable or disable the animations time capture
  93114. */
  93115. set: function (value) {
  93116. var _this = this;
  93117. if (value === this._captureAnimationsTime) {
  93118. return;
  93119. }
  93120. this._captureAnimationsTime = value;
  93121. if (value) {
  93122. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  93123. _this._animationsTime.endMonitoring();
  93124. });
  93125. }
  93126. else {
  93127. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93128. this._onAfterAnimationsObserver = null;
  93129. }
  93130. },
  93131. enumerable: true,
  93132. configurable: true
  93133. });
  93134. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  93135. /**
  93136. * Gets the perf counter used for frame time capture
  93137. */
  93138. get: function () {
  93139. return this._frameTime;
  93140. },
  93141. enumerable: true,
  93142. configurable: true
  93143. });
  93144. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  93145. /**
  93146. * Gets the frame time capture status
  93147. */
  93148. get: function () {
  93149. return this._captureFrameTime;
  93150. },
  93151. /**
  93152. * Enable or disable the frame time capture
  93153. */
  93154. set: function (value) {
  93155. this._captureFrameTime = value;
  93156. },
  93157. enumerable: true,
  93158. configurable: true
  93159. });
  93160. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  93161. /**
  93162. * Gets the perf counter used for inter-frames time capture
  93163. */
  93164. get: function () {
  93165. return this._interFrameTime;
  93166. },
  93167. enumerable: true,
  93168. configurable: true
  93169. });
  93170. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  93171. /**
  93172. * Gets the inter-frames time capture status
  93173. */
  93174. get: function () {
  93175. return this._captureInterFrameTime;
  93176. },
  93177. /**
  93178. * Enable or disable the inter-frames time capture
  93179. */
  93180. set: function (value) {
  93181. this._captureInterFrameTime = value;
  93182. },
  93183. enumerable: true,
  93184. configurable: true
  93185. });
  93186. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  93187. /**
  93188. * Gets the perf counter used for render time capture
  93189. */
  93190. get: function () {
  93191. return this._renderTime;
  93192. },
  93193. enumerable: true,
  93194. configurable: true
  93195. });
  93196. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  93197. /**
  93198. * Gets the render time capture status
  93199. */
  93200. get: function () {
  93201. return this._captureRenderTime;
  93202. },
  93203. /**
  93204. * Enable or disable the render time capture
  93205. */
  93206. set: function (value) {
  93207. var _this = this;
  93208. if (value === this._captureRenderTime) {
  93209. return;
  93210. }
  93211. this._captureRenderTime = value;
  93212. if (value) {
  93213. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  93214. _this._renderTime.beginMonitoring();
  93215. BABYLON.Tools.StartPerformanceCounter("Main render");
  93216. });
  93217. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  93218. _this._renderTime.endMonitoring(false);
  93219. BABYLON.Tools.EndPerformanceCounter("Main render");
  93220. });
  93221. }
  93222. else {
  93223. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93224. this._onBeforeDrawPhaseObserver = null;
  93225. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93226. this._onAfterDrawPhaseObserver = null;
  93227. }
  93228. },
  93229. enumerable: true,
  93230. configurable: true
  93231. });
  93232. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  93233. /**
  93234. * Gets the perf counter used for draw calls
  93235. */
  93236. get: function () {
  93237. return this.scene.getEngine()._drawCalls;
  93238. },
  93239. enumerable: true,
  93240. configurable: true
  93241. });
  93242. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  93243. /**
  93244. * Gets the perf counter used for texture collisions
  93245. */
  93246. get: function () {
  93247. return this.scene.getEngine()._textureCollisions;
  93248. },
  93249. enumerable: true,
  93250. configurable: true
  93251. });
  93252. SceneInstrumentation.prototype.dispose = function () {
  93253. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93254. this._onAfterRenderObserver = null;
  93255. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93256. this._onBeforeActiveMeshesEvaluationObserver = null;
  93257. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93258. this._onAfterActiveMeshesEvaluationObserver = null;
  93259. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93260. this._onBeforeRenderTargetsRenderObserver = null;
  93261. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93262. this._onAfterRenderTargetsRenderObserver = null;
  93263. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  93264. this._onBeforeAnimationsObserver = null;
  93265. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93266. this._onBeforeParticlesRenderingObserver = null;
  93267. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93268. this._onAfterParticlesRenderingObserver = null;
  93269. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93270. this._onBeforeSpritesRenderingObserver = null;
  93271. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93272. this._onAfterSpritesRenderingObserver = null;
  93273. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93274. this._onBeforeDrawPhaseObserver = null;
  93275. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93276. this._onAfterDrawPhaseObserver = null;
  93277. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93278. this._onBeforePhysicsObserver = null;
  93279. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93280. this._onAfterPhysicsObserver = null;
  93281. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93282. this._onAfterAnimationsObserver = null;
  93283. this.scene = null;
  93284. };
  93285. return SceneInstrumentation;
  93286. }());
  93287. BABYLON.SceneInstrumentation = SceneInstrumentation;
  93288. })(BABYLON || (BABYLON = {}));
  93289. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  93290. "use strict";
  93291. var BABYLON;
  93292. (function (BABYLON) {
  93293. var _TimeToken = /** @class */ (function () {
  93294. function _TimeToken() {
  93295. this._timeElapsedQueryEnded = false;
  93296. }
  93297. return _TimeToken;
  93298. }());
  93299. BABYLON._TimeToken = _TimeToken;
  93300. })(BABYLON || (BABYLON = {}));
  93301. //# sourceMappingURL=babylon.timeToken.js.map
  93302. "use strict";
  93303. var BABYLON;
  93304. (function (BABYLON) {
  93305. /**
  93306. * Background material defines definition.
  93307. * @ignore Mainly internal Use
  93308. */
  93309. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  93310. __extends(BackgroundMaterialDefines, _super);
  93311. /**
  93312. * Constructor of the defines.
  93313. */
  93314. function BackgroundMaterialDefines() {
  93315. var _this = _super.call(this) || this;
  93316. /**
  93317. * True if the diffuse texture is in use.
  93318. */
  93319. _this.DIFFUSE = false;
  93320. /**
  93321. * The direct UV channel to use.
  93322. */
  93323. _this.DIFFUSEDIRECTUV = 0;
  93324. /**
  93325. * True if the diffuse texture is in gamma space.
  93326. */
  93327. _this.GAMMADIFFUSE = false;
  93328. /**
  93329. * True if the diffuse texture has opacity in the alpha channel.
  93330. */
  93331. _this.DIFFUSEHASALPHA = false;
  93332. /**
  93333. * True if you want the material to fade to transparent at grazing angle.
  93334. */
  93335. _this.OPACITYFRESNEL = false;
  93336. /**
  93337. * True if an extra blur needs to be added in the reflection.
  93338. */
  93339. _this.REFLECTIONBLUR = false;
  93340. /**
  93341. * True if you want the material to fade to reflection at grazing angle.
  93342. */
  93343. _this.REFLECTIONFRESNEL = false;
  93344. /**
  93345. * True if you want the material to falloff as far as you move away from the scene center.
  93346. */
  93347. _this.REFLECTIONFALLOFF = false;
  93348. /**
  93349. * False if the current Webgl implementation does not support the texture lod extension.
  93350. */
  93351. _this.TEXTURELODSUPPORT = false;
  93352. /**
  93353. * True to ensure the data are premultiplied.
  93354. */
  93355. _this.PREMULTIPLYALPHA = false;
  93356. /**
  93357. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  93358. */
  93359. _this.USERGBCOLOR = false;
  93360. /**
  93361. * True to add noise in order to reduce the banding effect.
  93362. */
  93363. _this.NOISE = false;
  93364. /**
  93365. * is the reflection texture in BGR color scheme?
  93366. * Mainly used to solve a bug in ios10 video tag
  93367. */
  93368. _this.REFLECTIONBGR = false;
  93369. _this.IMAGEPROCESSING = false;
  93370. _this.VIGNETTE = false;
  93371. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  93372. _this.VIGNETTEBLENDMODEOPAQUE = false;
  93373. _this.TONEMAPPING = false;
  93374. _this.CONTRAST = false;
  93375. _this.COLORCURVES = false;
  93376. _this.COLORGRADING = false;
  93377. _this.COLORGRADING3D = false;
  93378. _this.SAMPLER3DGREENDEPTH = false;
  93379. _this.SAMPLER3DBGRMAP = false;
  93380. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  93381. _this.EXPOSURE = false;
  93382. // Reflection.
  93383. _this.REFLECTION = false;
  93384. _this.REFLECTIONMAP_3D = false;
  93385. _this.REFLECTIONMAP_SPHERICAL = false;
  93386. _this.REFLECTIONMAP_PLANAR = false;
  93387. _this.REFLECTIONMAP_CUBIC = false;
  93388. _this.REFLECTIONMAP_PROJECTION = false;
  93389. _this.REFLECTIONMAP_SKYBOX = false;
  93390. _this.REFLECTIONMAP_EXPLICIT = false;
  93391. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93392. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93393. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93394. _this.INVERTCUBICMAP = false;
  93395. _this.REFLECTIONMAP_OPPOSITEZ = false;
  93396. _this.LODINREFLECTIONALPHA = false;
  93397. _this.GAMMAREFLECTION = false;
  93398. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  93399. // Default BJS.
  93400. _this.MAINUV1 = false;
  93401. _this.MAINUV2 = false;
  93402. _this.UV1 = false;
  93403. _this.UV2 = false;
  93404. _this.CLIPPLANE = false;
  93405. _this.POINTSIZE = false;
  93406. _this.FOG = false;
  93407. _this.NORMAL = false;
  93408. _this.NUM_BONE_INFLUENCERS = 0;
  93409. _this.BonesPerMesh = 0;
  93410. _this.INSTANCES = false;
  93411. _this.SHADOWFLOAT = false;
  93412. _this.rebuild();
  93413. return _this;
  93414. }
  93415. return BackgroundMaterialDefines;
  93416. }(BABYLON.MaterialDefines));
  93417. /**
  93418. * Background material used to create an efficient environement around your scene.
  93419. */
  93420. var BackgroundMaterial = /** @class */ (function (_super) {
  93421. __extends(BackgroundMaterial, _super);
  93422. /**
  93423. * Instantiates a Background Material in the given scene
  93424. * @param name The friendly name of the material
  93425. * @param scene The scene to add the material to
  93426. */
  93427. function BackgroundMaterial(name, scene) {
  93428. var _this = _super.call(this, name, scene) || this;
  93429. /**
  93430. * Key light Color (multiply against the R channel of the environement texture)
  93431. */
  93432. _this.primaryColor = BABYLON.Color3.White();
  93433. /**
  93434. * Key light Level (allowing HDR output of the background)
  93435. */
  93436. _this.primaryLevel = 1;
  93437. /**
  93438. * Secondary light Color (multiply against the G channel of the environement texture)
  93439. */
  93440. _this.secondaryColor = BABYLON.Color3.Gray();
  93441. /**
  93442. * Secondary light Level (allowing HDR output of the background)
  93443. */
  93444. _this.secondaryLevel = 1;
  93445. /**
  93446. * Tertiary light Color (multiply against the B channel of the environement texture)
  93447. */
  93448. _this.tertiaryColor = BABYLON.Color3.Black();
  93449. /**
  93450. * Tertiary light Level (allowing HDR output of the background)
  93451. */
  93452. _this.tertiaryLevel = 1;
  93453. /**
  93454. * Reflection Texture used in the material.
  93455. * Should be author in a specific way for the best result (refer to the documentation).
  93456. */
  93457. _this.reflectionTexture = null;
  93458. /**
  93459. * Reflection Texture level of blur.
  93460. *
  93461. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  93462. * texture twice.
  93463. */
  93464. _this.reflectionBlur = 0;
  93465. /**
  93466. * Diffuse Texture used in the material.
  93467. * Should be author in a specific way for the best result (refer to the documentation).
  93468. */
  93469. _this.diffuseTexture = null;
  93470. _this._shadowLights = null;
  93471. /**
  93472. * Specify the list of lights casting shadow on the material.
  93473. * All scene shadow lights will be included if null.
  93474. */
  93475. _this.shadowLights = null;
  93476. /**
  93477. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  93478. * soft lighting on the background.
  93479. */
  93480. _this.shadowBlurScale = 1;
  93481. /**
  93482. * Helps adjusting the shadow to a softer level if required.
  93483. * 0 means black shadows and 1 means no shadows.
  93484. */
  93485. _this.shadowLevel = 0;
  93486. /**
  93487. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  93488. * It is usually zero but might be interesting to modify according to your setup.
  93489. */
  93490. _this.sceneCenter = BABYLON.Vector3.Zero();
  93491. /**
  93492. * This helps specifying that the material is falling off to the sky box at grazing angle.
  93493. * This helps ensuring a nice transition when the camera goes under the ground.
  93494. */
  93495. _this.opacityFresnel = true;
  93496. /**
  93497. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  93498. * This helps adding a mirror texture on the ground.
  93499. */
  93500. _this.reflectionFresnel = false;
  93501. /**
  93502. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  93503. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  93504. */
  93505. _this.reflectionFalloffDistance = 0.0;
  93506. /**
  93507. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  93508. */
  93509. _this.reflectionAmount = 1.0;
  93510. /**
  93511. * This specifies the weight of the reflection at grazing angle.
  93512. */
  93513. _this.reflectionReflectance0 = 0.05;
  93514. /**
  93515. * This specifies the weight of the reflection at a perpendicular point of view.
  93516. */
  93517. _this.reflectionReflectance90 = 0.5;
  93518. /**
  93519. * Helps to directly use the maps channels instead of their level.
  93520. */
  93521. _this.useRGBColor = true;
  93522. /**
  93523. * This helps reducing the banding effect that could occur on the background.
  93524. */
  93525. _this.enableNoise = false;
  93526. _this._fovMultiplier = 1.0;
  93527. /**
  93528. * Enable the FOV adjustment feature controlled by fovMultiplier.
  93529. */
  93530. _this.useEquirectangularFOV = false;
  93531. _this._maxSimultaneousLights = 4;
  93532. /**
  93533. * Number of Simultaneous lights allowed on the material.
  93534. */
  93535. _this.maxSimultaneousLights = 4;
  93536. /**
  93537. * Keep track of the image processing observer to allow dispose and replace.
  93538. */
  93539. _this._imageProcessingObserver = null;
  93540. /**
  93541. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  93542. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  93543. */
  93544. _this.switchToBGR = false;
  93545. // Temp values kept as cache in the material.
  93546. _this._renderTargets = new BABYLON.SmartArray(16);
  93547. _this._reflectionControls = BABYLON.Vector4.Zero();
  93548. // Setup the default processing configuration to the scene.
  93549. _this._attachImageProcessingConfiguration(null);
  93550. _this.getRenderTargetTextures = function () {
  93551. _this._renderTargets.reset();
  93552. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  93553. _this._renderTargets.push(_this._diffuseTexture);
  93554. }
  93555. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  93556. _this._renderTargets.push(_this._reflectionTexture);
  93557. }
  93558. return _this._renderTargets;
  93559. };
  93560. return _this;
  93561. }
  93562. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  93563. /**
  93564. * Sets the reflection reflectance fresnel values according to the default standard
  93565. * empirically know to work well :-)
  93566. */
  93567. set: function (value) {
  93568. var reflectionWeight = value;
  93569. if (reflectionWeight < 0.5) {
  93570. reflectionWeight = reflectionWeight * 2.0;
  93571. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  93572. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  93573. }
  93574. else {
  93575. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  93576. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  93577. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  93578. }
  93579. },
  93580. enumerable: true,
  93581. configurable: true
  93582. });
  93583. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  93584. /**
  93585. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  93586. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  93587. * Recommended to be keep at 1.0 except for special cases.
  93588. */
  93589. get: function () {
  93590. return this._fovMultiplier;
  93591. },
  93592. set: function (value) {
  93593. if (isNaN(value)) {
  93594. value = 1.0;
  93595. }
  93596. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  93597. },
  93598. enumerable: true,
  93599. configurable: true
  93600. });
  93601. /**
  93602. * Attaches a new image processing configuration to the PBR Material.
  93603. * @param configuration (if null the scene configuration will be use)
  93604. */
  93605. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  93606. var _this = this;
  93607. if (configuration === this._imageProcessingConfiguration) {
  93608. return;
  93609. }
  93610. // Detaches observer.
  93611. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  93612. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  93613. }
  93614. // Pick the scene configuration if needed.
  93615. if (!configuration) {
  93616. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  93617. }
  93618. else {
  93619. this._imageProcessingConfiguration = configuration;
  93620. }
  93621. // Attaches observer.
  93622. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  93623. _this._markAllSubMeshesAsImageProcessingDirty();
  93624. });
  93625. };
  93626. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  93627. /**
  93628. * Gets the image processing configuration used either in this material.
  93629. */
  93630. get: function () {
  93631. return this._imageProcessingConfiguration;
  93632. },
  93633. /**
  93634. * Sets the Default image processing configuration used either in the this material.
  93635. *
  93636. * If sets to null, the scene one is in use.
  93637. */
  93638. set: function (value) {
  93639. this._attachImageProcessingConfiguration(value);
  93640. // Ensure the effect will be rebuilt.
  93641. this._markAllSubMeshesAsTexturesDirty();
  93642. },
  93643. enumerable: true,
  93644. configurable: true
  93645. });
  93646. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  93647. /**
  93648. * Gets wether the color curves effect is enabled.
  93649. */
  93650. get: function () {
  93651. return this.imageProcessingConfiguration.colorCurvesEnabled;
  93652. },
  93653. /**
  93654. * Sets wether the color curves effect is enabled.
  93655. */
  93656. set: function (value) {
  93657. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  93658. },
  93659. enumerable: true,
  93660. configurable: true
  93661. });
  93662. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  93663. /**
  93664. * Gets wether the color grading effect is enabled.
  93665. */
  93666. get: function () {
  93667. return this.imageProcessingConfiguration.colorGradingEnabled;
  93668. },
  93669. /**
  93670. * Gets wether the color grading effect is enabled.
  93671. */
  93672. set: function (value) {
  93673. this.imageProcessingConfiguration.colorGradingEnabled = value;
  93674. },
  93675. enumerable: true,
  93676. configurable: true
  93677. });
  93678. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  93679. /**
  93680. * Gets wether tonemapping is enabled or not.
  93681. */
  93682. get: function () {
  93683. return this._imageProcessingConfiguration.toneMappingEnabled;
  93684. },
  93685. /**
  93686. * Sets wether tonemapping is enabled or not
  93687. */
  93688. set: function (value) {
  93689. this._imageProcessingConfiguration.toneMappingEnabled = value;
  93690. },
  93691. enumerable: true,
  93692. configurable: true
  93693. });
  93694. ;
  93695. ;
  93696. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  93697. /**
  93698. * The camera exposure used on this material.
  93699. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  93700. * This corresponds to a photographic exposure.
  93701. */
  93702. get: function () {
  93703. return this._imageProcessingConfiguration.exposure;
  93704. },
  93705. /**
  93706. * The camera exposure used on this material.
  93707. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  93708. * This corresponds to a photographic exposure.
  93709. */
  93710. set: function (value) {
  93711. this._imageProcessingConfiguration.exposure = value;
  93712. },
  93713. enumerable: true,
  93714. configurable: true
  93715. });
  93716. ;
  93717. ;
  93718. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  93719. /**
  93720. * Gets The camera contrast used on this material.
  93721. */
  93722. get: function () {
  93723. return this._imageProcessingConfiguration.contrast;
  93724. },
  93725. /**
  93726. * Sets The camera contrast used on this material.
  93727. */
  93728. set: function (value) {
  93729. this._imageProcessingConfiguration.contrast = value;
  93730. },
  93731. enumerable: true,
  93732. configurable: true
  93733. });
  93734. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  93735. /**
  93736. * Gets the Color Grading 2D Lookup Texture.
  93737. */
  93738. get: function () {
  93739. return this._imageProcessingConfiguration.colorGradingTexture;
  93740. },
  93741. /**
  93742. * Sets the Color Grading 2D Lookup Texture.
  93743. */
  93744. set: function (value) {
  93745. this.imageProcessingConfiguration.colorGradingTexture = value;
  93746. },
  93747. enumerable: true,
  93748. configurable: true
  93749. });
  93750. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  93751. /**
  93752. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  93753. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  93754. * 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;
  93755. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  93756. */
  93757. get: function () {
  93758. return this.imageProcessingConfiguration.colorCurves;
  93759. },
  93760. /**
  93761. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  93762. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  93763. * 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;
  93764. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  93765. */
  93766. set: function (value) {
  93767. this.imageProcessingConfiguration.colorCurves = value;
  93768. },
  93769. enumerable: true,
  93770. configurable: true
  93771. });
  93772. /**
  93773. * The entire material has been created in order to prevent overdraw.
  93774. * @returns false
  93775. */
  93776. BackgroundMaterial.prototype.needAlphaTesting = function () {
  93777. return true;
  93778. };
  93779. /**
  93780. * The entire material has been created in order to prevent overdraw.
  93781. * @returns true if blending is enable
  93782. */
  93783. BackgroundMaterial.prototype.needAlphaBlending = function () {
  93784. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  93785. };
  93786. /**
  93787. * Checks wether the material is ready to be rendered for a given mesh.
  93788. * @param mesh The mesh to render
  93789. * @param subMesh The submesh to check against
  93790. * @param useInstances Specify wether or not the material is used with instances
  93791. * @returns true if all the dependencies are ready (Textures, Effects...)
  93792. */
  93793. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  93794. var _this = this;
  93795. if (useInstances === void 0) { useInstances = false; }
  93796. if (subMesh.effect && this.isFrozen) {
  93797. if (this._wasPreviouslyReady) {
  93798. return true;
  93799. }
  93800. }
  93801. if (!subMesh._materialDefines) {
  93802. subMesh._materialDefines = new BackgroundMaterialDefines();
  93803. }
  93804. var scene = this.getScene();
  93805. var defines = subMesh._materialDefines;
  93806. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  93807. if (defines._renderId === scene.getRenderId()) {
  93808. return true;
  93809. }
  93810. }
  93811. var engine = scene.getEngine();
  93812. // Lights
  93813. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  93814. defines._needNormals = true;
  93815. // Textures
  93816. if (defines._areTexturesDirty) {
  93817. defines._needUVs = false;
  93818. if (scene.texturesEnabled) {
  93819. if (scene.getEngine().getCaps().textureLOD) {
  93820. defines.TEXTURELODSUPPORT = true;
  93821. }
  93822. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  93823. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  93824. return false;
  93825. }
  93826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  93827. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  93828. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  93829. defines.OPACITYFRESNEL = this._opacityFresnel;
  93830. }
  93831. else {
  93832. defines.DIFFUSE = false;
  93833. defines.DIFFUSEHASALPHA = false;
  93834. defines.GAMMADIFFUSE = false;
  93835. defines.OPACITYFRESNEL = false;
  93836. }
  93837. var reflectionTexture = this._reflectionTexture;
  93838. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  93839. if (!reflectionTexture.isReadyOrNotBlocking()) {
  93840. return false;
  93841. }
  93842. defines.REFLECTION = true;
  93843. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  93844. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  93845. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  93846. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  93847. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  93848. defines.REFLECTIONBGR = this.switchToBGR;
  93849. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  93850. defines.INVERTCUBICMAP = true;
  93851. }
  93852. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  93853. switch (reflectionTexture.coordinatesMode) {
  93854. case BABYLON.Texture.CUBIC_MODE:
  93855. case BABYLON.Texture.INVCUBIC_MODE:
  93856. defines.REFLECTIONMAP_CUBIC = true;
  93857. break;
  93858. case BABYLON.Texture.EXPLICIT_MODE:
  93859. defines.REFLECTIONMAP_EXPLICIT = true;
  93860. break;
  93861. case BABYLON.Texture.PLANAR_MODE:
  93862. defines.REFLECTIONMAP_PLANAR = true;
  93863. break;
  93864. case BABYLON.Texture.PROJECTION_MODE:
  93865. defines.REFLECTIONMAP_PROJECTION = true;
  93866. break;
  93867. case BABYLON.Texture.SKYBOX_MODE:
  93868. defines.REFLECTIONMAP_SKYBOX = true;
  93869. break;
  93870. case BABYLON.Texture.SPHERICAL_MODE:
  93871. defines.REFLECTIONMAP_SPHERICAL = true;
  93872. break;
  93873. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  93874. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  93875. break;
  93876. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  93877. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  93878. break;
  93879. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  93880. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  93881. break;
  93882. }
  93883. if (this.reflectionFresnel) {
  93884. defines.REFLECTIONFRESNEL = true;
  93885. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  93886. this._reflectionControls.x = this.reflectionAmount;
  93887. this._reflectionControls.y = this.reflectionReflectance0;
  93888. this._reflectionControls.z = this.reflectionReflectance90;
  93889. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  93890. }
  93891. else {
  93892. defines.REFLECTIONFRESNEL = false;
  93893. defines.REFLECTIONFALLOFF = false;
  93894. }
  93895. }
  93896. else {
  93897. defines.REFLECTION = false;
  93898. defines.REFLECTIONFALLOFF = false;
  93899. defines.REFLECTIONBLUR = false;
  93900. defines.REFLECTIONMAP_3D = false;
  93901. defines.REFLECTIONMAP_SPHERICAL = false;
  93902. defines.REFLECTIONMAP_PLANAR = false;
  93903. defines.REFLECTIONMAP_CUBIC = false;
  93904. defines.REFLECTIONMAP_PROJECTION = false;
  93905. defines.REFLECTIONMAP_SKYBOX = false;
  93906. defines.REFLECTIONMAP_EXPLICIT = false;
  93907. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93908. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93909. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93910. defines.INVERTCUBICMAP = false;
  93911. defines.REFLECTIONMAP_OPPOSITEZ = false;
  93912. defines.LODINREFLECTIONALPHA = false;
  93913. defines.GAMMAREFLECTION = false;
  93914. }
  93915. }
  93916. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  93917. defines.USERGBCOLOR = this._useRGBColor;
  93918. defines.NOISE = this._enableNoise;
  93919. }
  93920. if (defines._areImageProcessingDirty) {
  93921. if (!this._imageProcessingConfiguration.isReady()) {
  93922. return false;
  93923. }
  93924. this._imageProcessingConfiguration.prepareDefines(defines);
  93925. }
  93926. // Misc.
  93927. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  93928. // Values that need to be evaluated on every frame
  93929. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  93930. // Attribs
  93931. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  93932. if (mesh) {
  93933. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93934. mesh.createNormals(true);
  93935. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  93936. }
  93937. }
  93938. }
  93939. // Get correct effect
  93940. if (defines.isDirty) {
  93941. defines.markAsProcessed();
  93942. scene.resetCachedMaterial();
  93943. // Fallbacks
  93944. var fallbacks = new BABYLON.EffectFallbacks();
  93945. if (defines.FOG) {
  93946. fallbacks.addFallback(0, "FOG");
  93947. }
  93948. if (defines.POINTSIZE) {
  93949. fallbacks.addFallback(1, "POINTSIZE");
  93950. }
  93951. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  93952. if (defines.NUM_BONE_INFLUENCERS > 0) {
  93953. fallbacks.addCPUSkinningFallback(0, mesh);
  93954. }
  93955. //Attributes
  93956. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93957. if (defines.NORMAL) {
  93958. attribs.push(BABYLON.VertexBuffer.NormalKind);
  93959. }
  93960. if (defines.UV1) {
  93961. attribs.push(BABYLON.VertexBuffer.UVKind);
  93962. }
  93963. if (defines.UV2) {
  93964. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93965. }
  93966. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  93967. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  93968. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  93969. "vFogInfos", "vFogColor", "pointSize",
  93970. "vClipPlane", "mBones",
  93971. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  93972. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  93973. "shadowLevel", "alpha",
  93974. "vBackgroundCenter", "vReflectionControl",
  93975. "vDiffuseInfos", "diffuseMatrix",
  93976. ];
  93977. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  93978. var uniformBuffers = ["Material", "Scene"];
  93979. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  93980. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  93981. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  93982. uniformsNames: uniforms,
  93983. uniformBuffersNames: uniformBuffers,
  93984. samplers: samplers,
  93985. defines: defines,
  93986. maxSimultaneousLights: this._maxSimultaneousLights
  93987. });
  93988. var onCompiled = function (effect) {
  93989. if (_this.onCompiled) {
  93990. _this.onCompiled(effect);
  93991. }
  93992. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  93993. };
  93994. var join = defines.toString();
  93995. subMesh.setEffect(scene.getEngine().createEffect("background", {
  93996. attributes: attribs,
  93997. uniformsNames: uniforms,
  93998. uniformBuffersNames: uniformBuffers,
  93999. samplers: samplers,
  94000. defines: join,
  94001. fallbacks: fallbacks,
  94002. onCompiled: onCompiled,
  94003. onError: this.onError,
  94004. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  94005. }, engine), defines);
  94006. this.buildUniformLayout();
  94007. }
  94008. if (!subMesh.effect || !subMesh.effect.isReady()) {
  94009. return false;
  94010. }
  94011. defines._renderId = scene.getRenderId();
  94012. this._wasPreviouslyReady = true;
  94013. return true;
  94014. };
  94015. /**
  94016. * Build the uniform buffer used in the material.
  94017. */
  94018. BackgroundMaterial.prototype.buildUniformLayout = function () {
  94019. // Order is important !
  94020. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  94021. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  94022. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  94023. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  94024. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  94025. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  94026. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  94027. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  94028. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  94029. this._uniformBuffer.addUniform("pointSize", 1);
  94030. this._uniformBuffer.addUniform("shadowLevel", 1);
  94031. this._uniformBuffer.addUniform("alpha", 1);
  94032. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  94033. this._uniformBuffer.addUniform("vReflectionControl", 4);
  94034. this._uniformBuffer.create();
  94035. };
  94036. /**
  94037. * Unbind the material.
  94038. */
  94039. BackgroundMaterial.prototype.unbind = function () {
  94040. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  94041. this._uniformBuffer.setTexture("diffuseSampler", null);
  94042. }
  94043. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  94044. this._uniformBuffer.setTexture("reflectionSampler", null);
  94045. }
  94046. _super.prototype.unbind.call(this);
  94047. };
  94048. /**
  94049. * Bind only the world matrix to the material.
  94050. * @param world The world matrix to bind.
  94051. */
  94052. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  94053. this._activeEffect.setMatrix("world", world);
  94054. };
  94055. /**
  94056. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  94057. * @param world The world matrix to bind.
  94058. * @param subMesh The submesh to bind for.
  94059. */
  94060. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  94061. var scene = this.getScene();
  94062. var defines = subMesh._materialDefines;
  94063. if (!defines) {
  94064. return;
  94065. }
  94066. var effect = subMesh.effect;
  94067. if (!effect) {
  94068. return;
  94069. }
  94070. this._activeEffect = effect;
  94071. // Matrices
  94072. this.bindOnlyWorldMatrix(world);
  94073. // Bones
  94074. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  94075. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  94076. if (mustRebind) {
  94077. this._uniformBuffer.bindToEffect(effect, "Material");
  94078. this.bindViewProjection(effect);
  94079. var reflectionTexture = this._reflectionTexture;
  94080. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  94081. // Texture uniforms
  94082. if (scene.texturesEnabled) {
  94083. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94084. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  94085. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  94086. }
  94087. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94088. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  94089. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  94090. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  94091. }
  94092. }
  94093. if (this.shadowLevel > 0) {
  94094. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  94095. }
  94096. this._uniformBuffer.updateFloat("alpha", this.alpha);
  94097. // Point size
  94098. if (this.pointsCloud) {
  94099. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  94100. }
  94101. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  94102. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  94103. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  94104. }
  94105. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  94106. // Textures
  94107. if (scene.texturesEnabled) {
  94108. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94109. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  94110. }
  94111. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94112. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  94113. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94114. }
  94115. else if (!defines.REFLECTIONBLUR) {
  94116. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94117. }
  94118. else {
  94119. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  94120. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  94121. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  94122. }
  94123. if (defines.REFLECTIONFRESNEL) {
  94124. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  94125. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  94126. }
  94127. }
  94128. }
  94129. // Clip plane
  94130. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  94131. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  94132. }
  94133. if (mustRebind || !this.isFrozen) {
  94134. if (scene.lightsEnabled) {
  94135. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  94136. }
  94137. // View
  94138. this.bindView(effect);
  94139. // Fog
  94140. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  94141. // image processing
  94142. this._imageProcessingConfiguration.bind(this._activeEffect);
  94143. }
  94144. this._uniformBuffer.update();
  94145. this._afterBind(mesh);
  94146. };
  94147. /**
  94148. * Dispose the material.
  94149. * @param forceDisposeEffect Force disposal of the associated effect.
  94150. * @param forceDisposeTextures Force disposal of the associated textures.
  94151. */
  94152. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  94153. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  94154. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  94155. if (forceDisposeTextures) {
  94156. if (this.diffuseTexture) {
  94157. this.diffuseTexture.dispose();
  94158. }
  94159. if (this.reflectionTexture) {
  94160. this.reflectionTexture.dispose();
  94161. }
  94162. }
  94163. this._renderTargets.dispose();
  94164. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94165. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94166. }
  94167. _super.prototype.dispose.call(this, forceDisposeEffect);
  94168. };
  94169. /**
  94170. * Clones the material.
  94171. * @param name The cloned name.
  94172. * @returns The cloned material.
  94173. */
  94174. BackgroundMaterial.prototype.clone = function (name) {
  94175. var _this = this;
  94176. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  94177. };
  94178. /**
  94179. * Serializes the current material to its JSON representation.
  94180. * @returns The JSON representation.
  94181. */
  94182. BackgroundMaterial.prototype.serialize = function () {
  94183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94184. serializationObject.customType = "BABYLON.BackgroundMaterial";
  94185. return serializationObject;
  94186. };
  94187. /**
  94188. * Gets the class name of the material
  94189. * @returns "BackgroundMaterial"
  94190. */
  94191. BackgroundMaterial.prototype.getClassName = function () {
  94192. return "BackgroundMaterial";
  94193. };
  94194. /**
  94195. * Parse a JSON input to create back a background material.
  94196. * @param source The JSON data to parse
  94197. * @param scene The scene to create the parsed material in
  94198. * @param rootUrl The root url of the assets the material depends upon
  94199. * @returns the instantiated BackgroundMaterial.
  94200. */
  94201. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  94202. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  94203. };
  94204. /**
  94205. * Standard reflectance value at parallel view angle.
  94206. */
  94207. BackgroundMaterial.StandardReflectance0 = 0.05;
  94208. /**
  94209. * Standard reflectance value at grazing angle.
  94210. */
  94211. BackgroundMaterial.StandardReflectance90 = 0.5;
  94212. __decorate([
  94213. BABYLON.serializeAsColor3()
  94214. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  94215. __decorate([
  94216. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94217. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  94218. __decorate([
  94219. BABYLON.serialize()
  94220. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  94221. __decorate([
  94222. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94223. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  94224. __decorate([
  94225. BABYLON.serializeAsColor3()
  94226. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  94227. __decorate([
  94228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94229. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  94230. __decorate([
  94231. BABYLON.serialize()
  94232. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  94233. __decorate([
  94234. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94235. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  94236. __decorate([
  94237. BABYLON.serializeAsColor3()
  94238. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  94239. __decorate([
  94240. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94241. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  94242. __decorate([
  94243. BABYLON.serialize()
  94244. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  94245. __decorate([
  94246. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94247. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  94248. __decorate([
  94249. BABYLON.serializeAsTexture()
  94250. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  94251. __decorate([
  94252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94253. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  94254. __decorate([
  94255. BABYLON.serialize()
  94256. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  94257. __decorate([
  94258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94259. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  94260. __decorate([
  94261. BABYLON.serializeAsTexture()
  94262. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  94263. __decorate([
  94264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94265. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  94266. __decorate([
  94267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94268. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  94269. __decorate([
  94270. BABYLON.serialize()
  94271. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  94272. __decorate([
  94273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94274. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  94275. __decorate([
  94276. BABYLON.serialize()
  94277. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  94278. __decorate([
  94279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94280. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  94281. __decorate([
  94282. BABYLON.serializeAsVector3()
  94283. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  94284. __decorate([
  94285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94286. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  94287. __decorate([
  94288. BABYLON.serialize()
  94289. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  94290. __decorate([
  94291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94292. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  94293. __decorate([
  94294. BABYLON.serialize()
  94295. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  94296. __decorate([
  94297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94298. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  94299. __decorate([
  94300. BABYLON.serialize()
  94301. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  94302. __decorate([
  94303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94304. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  94305. __decorate([
  94306. BABYLON.serialize()
  94307. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  94308. __decorate([
  94309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94310. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  94311. __decorate([
  94312. BABYLON.serialize()
  94313. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  94314. __decorate([
  94315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94316. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  94317. __decorate([
  94318. BABYLON.serialize()
  94319. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  94320. __decorate([
  94321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94322. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  94323. __decorate([
  94324. BABYLON.serialize()
  94325. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  94326. __decorate([
  94327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94328. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  94329. __decorate([
  94330. BABYLON.serialize()
  94331. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  94332. __decorate([
  94333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94334. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  94335. __decorate([
  94336. BABYLON.serialize()
  94337. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  94338. __decorate([
  94339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94340. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  94341. __decorate([
  94342. BABYLON.serializeAsImageProcessingConfiguration()
  94343. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  94344. return BackgroundMaterial;
  94345. }(BABYLON.PushMaterial));
  94346. BABYLON.BackgroundMaterial = BackgroundMaterial;
  94347. })(BABYLON || (BABYLON = {}));
  94348. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  94349. "use strict";
  94350. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94351. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94352. s = arguments[i];
  94353. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94354. t[p] = s[p];
  94355. }
  94356. return t;
  94357. };
  94358. var BABYLON;
  94359. (function (BABYLON) {
  94360. /**
  94361. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  94362. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  94363. * It also helps with the default setup of your imageProcessing configuration.
  94364. */
  94365. var EnvironmentHelper = /** @class */ (function () {
  94366. /**
  94367. * constructor
  94368. * @param options
  94369. * @param scene The scene to add the material to
  94370. */
  94371. function EnvironmentHelper(options, scene) {
  94372. var _this = this;
  94373. this._errorHandler = function (message, exception) {
  94374. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  94375. };
  94376. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  94377. this._scene = scene;
  94378. this.onErrorObservable = new BABYLON.Observable();
  94379. this._setupBackground();
  94380. this._setupImageProcessing();
  94381. }
  94382. /**
  94383. * Creates the default options for the helper.
  94384. */
  94385. EnvironmentHelper._getDefaultOptions = function () {
  94386. return {
  94387. createGround: true,
  94388. groundSize: 15,
  94389. groundTexture: this._groundTextureCDNUrl,
  94390. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94391. groundOpacity: 0.9,
  94392. enableGroundShadow: true,
  94393. groundShadowLevel: 0.5,
  94394. enableGroundMirror: false,
  94395. groundMirrorSizeRatio: 0.3,
  94396. groundMirrorBlurKernel: 64,
  94397. groundMirrorAmount: 1,
  94398. groundMirrorFresnelWeight: 1,
  94399. groundMirrorFallOffDistance: 0,
  94400. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  94401. groundYBias: 0.00001,
  94402. createSkybox: true,
  94403. skyboxSize: 20,
  94404. skyboxTexture: this._skyboxTextureCDNUrl,
  94405. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94406. backgroundYRotation: 0,
  94407. sizeAuto: true,
  94408. rootPosition: BABYLON.Vector3.Zero(),
  94409. setupImageProcessing: true,
  94410. environmentTexture: this._environmentTextureCDNUrl,
  94411. cameraExposure: 0.8,
  94412. cameraContrast: 1.2,
  94413. toneMappingEnabled: true,
  94414. };
  94415. };
  94416. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  94417. /**
  94418. * Gets the root mesh created by the helper.
  94419. */
  94420. get: function () {
  94421. return this._rootMesh;
  94422. },
  94423. enumerable: true,
  94424. configurable: true
  94425. });
  94426. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  94427. /**
  94428. * Gets the skybox created by the helper.
  94429. */
  94430. get: function () {
  94431. return this._skybox;
  94432. },
  94433. enumerable: true,
  94434. configurable: true
  94435. });
  94436. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  94437. /**
  94438. * Gets the skybox texture created by the helper.
  94439. */
  94440. get: function () {
  94441. return this._skyboxTexture;
  94442. },
  94443. enumerable: true,
  94444. configurable: true
  94445. });
  94446. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  94447. /**
  94448. * Gets the skybox material created by the helper.
  94449. */
  94450. get: function () {
  94451. return this._skyboxMaterial;
  94452. },
  94453. enumerable: true,
  94454. configurable: true
  94455. });
  94456. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  94457. /**
  94458. * Gets the ground mesh created by the helper.
  94459. */
  94460. get: function () {
  94461. return this._ground;
  94462. },
  94463. enumerable: true,
  94464. configurable: true
  94465. });
  94466. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  94467. /**
  94468. * Gets the ground texture created by the helper.
  94469. */
  94470. get: function () {
  94471. return this._groundTexture;
  94472. },
  94473. enumerable: true,
  94474. configurable: true
  94475. });
  94476. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  94477. /**
  94478. * Gets the ground mirror created by the helper.
  94479. */
  94480. get: function () {
  94481. return this._groundMirror;
  94482. },
  94483. enumerable: true,
  94484. configurable: true
  94485. });
  94486. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  94487. /**
  94488. * Gets the ground mirror render list to helps pushing the meshes
  94489. * you wish in the ground reflection.
  94490. */
  94491. get: function () {
  94492. if (this._groundMirror) {
  94493. return this._groundMirror.renderList;
  94494. }
  94495. return null;
  94496. },
  94497. enumerable: true,
  94498. configurable: true
  94499. });
  94500. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  94501. /**
  94502. * Gets the ground material created by the helper.
  94503. */
  94504. get: function () {
  94505. return this._groundMaterial;
  94506. },
  94507. enumerable: true,
  94508. configurable: true
  94509. });
  94510. /**
  94511. * Updates the background according to the new options
  94512. * @param options
  94513. */
  94514. EnvironmentHelper.prototype.updateOptions = function (options) {
  94515. var newOptions = __assign({}, this._options, options);
  94516. if (this._ground && !newOptions.createGround) {
  94517. this._ground.dispose();
  94518. this._ground = null;
  94519. }
  94520. if (this._groundMaterial && !newOptions.createGround) {
  94521. this._groundMaterial.dispose();
  94522. this._groundMaterial = null;
  94523. }
  94524. if (this._groundTexture) {
  94525. if (this._options.groundTexture != newOptions.groundTexture) {
  94526. this._groundTexture.dispose();
  94527. this._groundTexture = null;
  94528. }
  94529. }
  94530. if (this._skybox && !newOptions.createSkybox) {
  94531. this._skybox.dispose();
  94532. this._skybox = null;
  94533. }
  94534. if (this._skyboxMaterial && !newOptions.createSkybox) {
  94535. this._skyboxMaterial.dispose();
  94536. this._skyboxMaterial = null;
  94537. }
  94538. if (this._skyboxTexture) {
  94539. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  94540. this._skyboxTexture.dispose();
  94541. this._skyboxTexture = null;
  94542. }
  94543. }
  94544. if (this._groundMirror && !newOptions.enableGroundMirror) {
  94545. this._groundMirror.dispose();
  94546. this._groundMirror = null;
  94547. }
  94548. if (this._scene.environmentTexture) {
  94549. if (this._options.environmentTexture != newOptions.environmentTexture) {
  94550. this._scene.environmentTexture.dispose();
  94551. }
  94552. }
  94553. this._options = newOptions;
  94554. this._setupBackground();
  94555. this._setupImageProcessing();
  94556. };
  94557. /**
  94558. * Sets the primary color of all the available elements.
  94559. * @param color
  94560. */
  94561. EnvironmentHelper.prototype.setMainColor = function (color) {
  94562. if (this.groundMaterial) {
  94563. this.groundMaterial.primaryColor = color;
  94564. }
  94565. if (this.skyboxMaterial) {
  94566. this.skyboxMaterial.primaryColor = color;
  94567. }
  94568. if (this.groundMirror) {
  94569. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  94570. }
  94571. };
  94572. /**
  94573. * Setup the image processing according to the specified options.
  94574. */
  94575. EnvironmentHelper.prototype._setupImageProcessing = function () {
  94576. if (this._options.setupImageProcessing) {
  94577. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  94578. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  94579. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  94580. this._setupEnvironmentTexture();
  94581. }
  94582. };
  94583. /**
  94584. * Setup the environment texture according to the specified options.
  94585. */
  94586. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  94587. if (this._scene.environmentTexture) {
  94588. return;
  94589. }
  94590. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  94591. this._scene.environmentTexture = this._options.environmentTexture;
  94592. return;
  94593. }
  94594. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  94595. this._scene.environmentTexture = environmentTexture;
  94596. };
  94597. /**
  94598. * Setup the background according to the specified options.
  94599. */
  94600. EnvironmentHelper.prototype._setupBackground = function () {
  94601. if (!this._rootMesh) {
  94602. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  94603. }
  94604. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  94605. var sceneSize = this._getSceneSize();
  94606. if (this._options.createGround) {
  94607. this._setupGround(sceneSize);
  94608. this._setupGroundMaterial();
  94609. this._setupGroundDiffuseTexture();
  94610. if (this._options.enableGroundMirror) {
  94611. this._setupGroundMirrorTexture(sceneSize);
  94612. }
  94613. this._setupMirrorInGroundMaterial();
  94614. }
  94615. if (this._options.createSkybox) {
  94616. this._setupSkybox(sceneSize);
  94617. this._setupSkyboxMaterial();
  94618. this._setupSkyboxReflectionTexture();
  94619. }
  94620. this._rootMesh.position.x = sceneSize.rootPosition.x;
  94621. this._rootMesh.position.z = sceneSize.rootPosition.z;
  94622. this._rootMesh.position.y = sceneSize.rootPosition.y;
  94623. };
  94624. /**
  94625. * Get the scene sizes according to the setup.
  94626. */
  94627. EnvironmentHelper.prototype._getSceneSize = function () {
  94628. var _this = this;
  94629. var groundSize = this._options.groundSize;
  94630. var skyboxSize = this._options.skyboxSize;
  94631. var rootPosition = this._options.rootPosition;
  94632. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  94633. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  94634. }
  94635. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  94636. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  94637. });
  94638. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  94639. if (this._options.sizeAuto) {
  94640. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  94641. this._scene.activeCamera.upperRadiusLimit) {
  94642. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  94643. skyboxSize = groundSize;
  94644. }
  94645. var sceneDiagonalLenght = sceneDiagonal.length();
  94646. if (sceneDiagonalLenght > groundSize) {
  94647. groundSize = sceneDiagonalLenght * 2;
  94648. skyboxSize = groundSize;
  94649. }
  94650. // 10 % bigger.
  94651. groundSize *= 1.1;
  94652. skyboxSize *= 1.5;
  94653. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  94654. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  94655. }
  94656. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  94657. };
  94658. /**
  94659. * Setup the ground according to the specified options.
  94660. */
  94661. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  94662. var _this = this;
  94663. if (!this._ground) {
  94664. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  94665. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  94666. this._ground.parent = this._rootMesh;
  94667. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  94668. }
  94669. this._ground.receiveShadows = this._options.enableGroundShadow;
  94670. };
  94671. /**
  94672. * Setup the ground material according to the specified options.
  94673. */
  94674. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  94675. if (!this._groundMaterial) {
  94676. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  94677. }
  94678. this._groundMaterial.alpha = this._options.groundOpacity;
  94679. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  94680. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  94681. this._groundMaterial.primaryLevel = 1;
  94682. this._groundMaterial.primaryColor = this._options.groundColor;
  94683. this._groundMaterial.secondaryLevel = 0;
  94684. this._groundMaterial.tertiaryLevel = 0;
  94685. this._groundMaterial.useRGBColor = false;
  94686. this._groundMaterial.enableNoise = true;
  94687. if (this._ground) {
  94688. this._ground.material = this._groundMaterial;
  94689. }
  94690. };
  94691. /**
  94692. * Setup the ground diffuse texture according to the specified options.
  94693. */
  94694. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  94695. if (!this._groundMaterial) {
  94696. return;
  94697. }
  94698. if (this._groundTexture) {
  94699. return;
  94700. }
  94701. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  94702. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  94703. return;
  94704. }
  94705. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  94706. diffuseTexture.gammaSpace = false;
  94707. diffuseTexture.hasAlpha = true;
  94708. this._groundMaterial.diffuseTexture = diffuseTexture;
  94709. };
  94710. /**
  94711. * Setup the ground mirror texture according to the specified options.
  94712. */
  94713. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  94714. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94715. if (!this._groundMirror) {
  94716. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  94717. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  94718. this._groundMirror.anisotropicFilteringLevel = 1;
  94719. this._groundMirror.wrapU = wrapping;
  94720. this._groundMirror.wrapV = wrapping;
  94721. this._groundMirror.gammaSpace = false;
  94722. if (this._groundMirror.renderList) {
  94723. for (var i = 0; i < this._scene.meshes.length; i++) {
  94724. var mesh = this._scene.meshes[i];
  94725. if (mesh !== this._ground &&
  94726. mesh !== this._skybox &&
  94727. mesh !== this._rootMesh) {
  94728. this._groundMirror.renderList.push(mesh);
  94729. }
  94730. }
  94731. }
  94732. }
  94733. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  94734. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  94735. };
  94736. /**
  94737. * Setup the ground to receive the mirror texture.
  94738. */
  94739. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  94740. if (this._groundMaterial) {
  94741. this._groundMaterial.reflectionTexture = this._groundMirror;
  94742. this._groundMaterial.reflectionFresnel = true;
  94743. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  94744. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  94745. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  94746. }
  94747. };
  94748. /**
  94749. * Setup the skybox according to the specified options.
  94750. */
  94751. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  94752. var _this = this;
  94753. if (!this._skybox) {
  94754. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  94755. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  94756. }
  94757. this._skybox.parent = this._rootMesh;
  94758. };
  94759. /**
  94760. * Setup the skybox material according to the specified options.
  94761. */
  94762. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  94763. if (!this._skybox) {
  94764. return;
  94765. }
  94766. if (!this._skyboxMaterial) {
  94767. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  94768. }
  94769. this._skyboxMaterial.useRGBColor = false;
  94770. this._skyboxMaterial.primaryLevel = 1;
  94771. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  94772. this._skyboxMaterial.secondaryLevel = 0;
  94773. this._skyboxMaterial.tertiaryLevel = 0;
  94774. this._skyboxMaterial.enableNoise = true;
  94775. this._skybox.material = this._skyboxMaterial;
  94776. };
  94777. /**
  94778. * Setup the skybox reflection texture according to the specified options.
  94779. */
  94780. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  94781. if (!this._skyboxMaterial) {
  94782. return;
  94783. }
  94784. if (this._skyboxTexture) {
  94785. return;
  94786. }
  94787. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  94788. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  94789. return;
  94790. }
  94791. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  94792. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  94793. this._skyboxTexture.gammaSpace = false;
  94794. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  94795. };
  94796. /**
  94797. * Dispose all the elements created by the Helper.
  94798. */
  94799. EnvironmentHelper.prototype.dispose = function () {
  94800. if (this._groundMaterial) {
  94801. this._groundMaterial.dispose(true, true);
  94802. }
  94803. if (this._skyboxMaterial) {
  94804. this._skyboxMaterial.dispose(true, true);
  94805. }
  94806. this._rootMesh.dispose(false);
  94807. };
  94808. /**
  94809. * Default ground texture URL.
  94810. */
  94811. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  94812. /**
  94813. * Default skybox texture URL.
  94814. */
  94815. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  94816. /**
  94817. * Default environment texture URL.
  94818. */
  94819. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  94820. return EnvironmentHelper;
  94821. }());
  94822. BABYLON.EnvironmentHelper = EnvironmentHelper;
  94823. })(BABYLON || (BABYLON = {}));
  94824. //# sourceMappingURL=babylon.environmentHelper.js.map
  94825. "use strict";
  94826. var BABYLON;
  94827. (function (BABYLON) {
  94828. /**
  94829. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  94830. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  94831. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  94832. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  94833. */
  94834. var VideoDome = /** @class */ (function (_super) {
  94835. __extends(VideoDome, _super);
  94836. /**
  94837. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  94838. * @param name Element's name, child elements will append suffixes for their own names.
  94839. * @param urlsOrVideo
  94840. * @param options An object containing optional or exposed sub element properties:
  94841. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  94842. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  94843. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  94844. * @param options **loop=true** Automatically loop video on end.
  94845. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  94846. */
  94847. function VideoDome(name, urlsOrVideo, options, scene) {
  94848. var _this = _super.call(this, name, scene) || this;
  94849. // set defaults and manage values
  94850. name = name || "videoDome";
  94851. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  94852. options.clickToPlay = Boolean(options.clickToPlay);
  94853. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  94854. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  94855. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  94856. // create
  94857. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  94858. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  94859. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  94860. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  94861. flat: false,
  94862. radius: options.size,
  94863. subdivisions: options.resolution,
  94864. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  94865. }, scene);
  94866. // configure material
  94867. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  94868. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  94869. material.reflectionTexture = _this._videoTexture;
  94870. material.useEquirectangularFOV = true;
  94871. material.fovMultiplier = 1.0;
  94872. // configure mesh
  94873. _this._mesh.material = material;
  94874. _this._mesh.parent = _this;
  94875. // optional configuration
  94876. if (options.clickToPlay) {
  94877. scene.onPointerUp = function () {
  94878. _this._videoTexture.video.play();
  94879. };
  94880. }
  94881. return _this;
  94882. }
  94883. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  94884. /**
  94885. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94886. * Also see the options.resolution property.
  94887. */
  94888. get: function () {
  94889. return this._material.fovMultiplier;
  94890. },
  94891. set: function (value) {
  94892. this._material.fovMultiplier = value;
  94893. },
  94894. enumerable: true,
  94895. configurable: true
  94896. });
  94897. /**
  94898. * Releases resources associated with this node.
  94899. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  94900. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  94901. */
  94902. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  94903. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  94904. this._videoTexture.dispose();
  94905. this._mesh.dispose();
  94906. this._material.dispose();
  94907. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  94908. };
  94909. return VideoDome;
  94910. }(BABYLON.Node));
  94911. BABYLON.VideoDome = VideoDome;
  94912. })(BABYLON || (BABYLON = {}));
  94913. //# sourceMappingURL=babylon.videoDome.js.map
  94914. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  94915. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  94916. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94917. globalObject["BABYLON"] = BABYLON;
  94918. //backwards compatibility
  94919. if(typeof earcut !== 'undefined') {
  94920. globalObject["Earcut"] = {
  94921. earcut: earcut
  94922. };
  94923. }
  94924. return BABYLON;
  94925. });
  94926. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  94927. /***/ }),
  94928. /* 1 */
  94929. /***/ (function(module, exports, __webpack_require__) {
  94930. "use strict";
  94931. Object.defineProperty(exports, "__esModule", { value: true });
  94932. var babylonjs_1 = __webpack_require__(0);
  94933. var helper_1 = __webpack_require__(3);
  94934. var HTMLMapper = (function () {
  94935. function HTMLMapper() {
  94936. }
  94937. HTMLMapper.prototype.map = function (element) {
  94938. var config = {};
  94939. var _loop_1 = function (attrIdx) {
  94940. var attr = element.attributes.item(attrIdx);
  94941. var split = attr.nodeName.split('.');
  94942. split.reduce(function (currentConfig, key, idx) {
  94943. var camelKey = helper_1.kebabToCamel(key);
  94944. if (idx === split.length - 1) {
  94945. var val = attr.nodeValue;
  94946. if (val === "true") {
  94947. val = true;
  94948. }
  94949. else if (val === "false") {
  94950. val = false;
  94951. }
  94952. else {
  94953. var isnum = /^\d+$/.test(val);
  94954. if (isnum) {
  94955. var number = parseFloat(val);
  94956. if (!isNaN(number)) {
  94957. val = number;
  94958. }
  94959. }
  94960. }
  94961. currentConfig[camelKey] = val;
  94962. }
  94963. else {
  94964. currentConfig[camelKey] = currentConfig[camelKey] || {};
  94965. }
  94966. return currentConfig[camelKey];
  94967. }, config);
  94968. };
  94969. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  94970. _loop_1(attrIdx);
  94971. }
  94972. return config;
  94973. };
  94974. return HTMLMapper;
  94975. }());
  94976. var JSONMapper = (function () {
  94977. function JSONMapper() {
  94978. }
  94979. JSONMapper.prototype.map = function (rawSource) {
  94980. return JSON.parse(rawSource);
  94981. };
  94982. return JSONMapper;
  94983. }());
  94984. var DOMMapper = (function () {
  94985. function DOMMapper() {
  94986. }
  94987. DOMMapper.prototype.map = function (baseElement) {
  94988. var htmlMapper = new HTMLMapper();
  94989. var config = htmlMapper.map(baseElement);
  94990. var traverseChildren = function (element, partConfig) {
  94991. var children = element.children;
  94992. if (children.length) {
  94993. for (var i = 0; i < children.length; ++i) {
  94994. var item = children.item(i);
  94995. var configMapped = htmlMapper.map(item);
  94996. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  94997. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  94998. partConfig[key] = [];
  94999. }
  95000. else {
  95001. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  95002. partConfig.push(configMapped);
  95003. }
  95004. else if (partConfig[key]) {
  95005. element.setAttribute('array', 'true');
  95006. var oldItem = partConfig[key];
  95007. partConfig = [oldItem, configMapped];
  95008. }
  95009. else {
  95010. partConfig[key] = configMapped;
  95011. }
  95012. }
  95013. traverseChildren(item, partConfig[key] || configMapped);
  95014. }
  95015. }
  95016. return partConfig;
  95017. };
  95018. traverseChildren(baseElement, config);
  95019. return config;
  95020. };
  95021. return DOMMapper;
  95022. }());
  95023. var MapperManager = (function () {
  95024. function MapperManager() {
  95025. this._mappers = {
  95026. "html": new HTMLMapper(),
  95027. "json": new JSONMapper(),
  95028. "dom": new DOMMapper()
  95029. };
  95030. }
  95031. MapperManager.prototype.getMapper = function (type) {
  95032. if (!this._mappers[type]) {
  95033. babylonjs_1.Tools.Error("No mapper defined for " + type);
  95034. }
  95035. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  95036. };
  95037. MapperManager.prototype.registerMapper = function (type, mapper) {
  95038. this._mappers[type] = mapper;
  95039. };
  95040. MapperManager.prototype.dispose = function () {
  95041. this._mappers = {};
  95042. };
  95043. MapperManager.DefaultMapper = 'json';
  95044. return MapperManager;
  95045. }());
  95046. exports.MapperManager = MapperManager;
  95047. exports.mapperManager = new MapperManager();
  95048. /***/ }),
  95049. /* 2 */
  95050. /***/ (function(module, exports, __webpack_require__) {
  95051. (function (global, factory) {
  95052. true ? module.exports = factory() :
  95053. typeof define === 'function' && define.amd ? define(factory) :
  95054. (global.deepmerge = factory());
  95055. }(this, (function () { 'use strict';
  95056. var isMergeableObject = function isMergeableObject(value) {
  95057. return isNonNullObject(value)
  95058. && !isSpecial(value)
  95059. };
  95060. function isNonNullObject(value) {
  95061. return !!value && typeof value === 'object'
  95062. }
  95063. function isSpecial(value) {
  95064. var stringValue = Object.prototype.toString.call(value);
  95065. return stringValue === '[object RegExp]'
  95066. || stringValue === '[object Date]'
  95067. || isReactElement(value)
  95068. }
  95069. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  95070. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  95071. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  95072. function isReactElement(value) {
  95073. return value.$$typeof === REACT_ELEMENT_TYPE
  95074. }
  95075. function emptyTarget(val) {
  95076. return Array.isArray(val) ? [] : {}
  95077. }
  95078. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  95079. var clone = !optionsArgument || optionsArgument.clone !== false;
  95080. return (clone && isMergeableObject(value))
  95081. ? deepmerge(emptyTarget(value), value, optionsArgument)
  95082. : value
  95083. }
  95084. function defaultArrayMerge(target, source, optionsArgument) {
  95085. return target.concat(source).map(function(element) {
  95086. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  95087. })
  95088. }
  95089. function mergeObject(target, source, optionsArgument) {
  95090. var destination = {};
  95091. if (isMergeableObject(target)) {
  95092. Object.keys(target).forEach(function(key) {
  95093. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  95094. });
  95095. }
  95096. Object.keys(source).forEach(function(key) {
  95097. if (!isMergeableObject(source[key]) || !target[key]) {
  95098. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  95099. } else {
  95100. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  95101. }
  95102. });
  95103. return destination
  95104. }
  95105. function deepmerge(target, source, optionsArgument) {
  95106. var sourceIsArray = Array.isArray(source);
  95107. var targetIsArray = Array.isArray(target);
  95108. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  95109. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  95110. if (!sourceAndTargetTypesMatch) {
  95111. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  95112. } else if (sourceIsArray) {
  95113. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  95114. return arrayMerge(target, source, optionsArgument)
  95115. } else {
  95116. return mergeObject(target, source, optionsArgument)
  95117. }
  95118. }
  95119. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  95120. if (!Array.isArray(array)) {
  95121. throw new Error('first argument should be an array')
  95122. }
  95123. return array.reduce(function(prev, next) {
  95124. return deepmerge(prev, next, optionsArgument)
  95125. }, {})
  95126. };
  95127. var deepmerge_1 = deepmerge;
  95128. return deepmerge_1;
  95129. })));
  95130. /***/ }),
  95131. /* 3 */
  95132. /***/ (function(module, exports, __webpack_require__) {
  95133. "use strict";
  95134. Object.defineProperty(exports, "__esModule", { value: true });
  95135. function isUrl(urlToCheck) {
  95136. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  95137. return true;
  95138. }
  95139. return false;
  95140. }
  95141. exports.isUrl = isUrl;
  95142. function kebabToCamel(s) {
  95143. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  95144. }
  95145. exports.kebabToCamel = kebabToCamel;
  95146. function camelToKebab(str) {
  95147. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  95148. }
  95149. exports.camelToKebab = camelToKebab;
  95150. /***/ }),
  95151. /* 4 */
  95152. /***/ (function(module, exports, __webpack_require__) {
  95153. "use strict";
  95154. Object.defineProperty(exports, "__esModule", { value: true });
  95155. var babylonjs_1 = __webpack_require__(0);
  95156. var ViewerManager = (function () {
  95157. function ViewerManager() {
  95158. this._viewers = {};
  95159. this.onViewerAddedObservable = new babylonjs_1.Observable();
  95160. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  95161. }
  95162. ViewerManager.prototype.addViewer = function (viewer) {
  95163. this._viewers[viewer.getBaseId()] = viewer;
  95164. this._onViewerAdded(viewer);
  95165. };
  95166. ViewerManager.prototype.removeViewer = function (viewer) {
  95167. var id = viewer.getBaseId();
  95168. delete this._viewers[id];
  95169. this.onViewerRemovedObservable.notifyObservers(id);
  95170. };
  95171. ViewerManager.prototype.getViewerById = function (id) {
  95172. return this._viewers[id];
  95173. };
  95174. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  95175. for (var id in this._viewers) {
  95176. if (this._viewers[id].containerElement === element) {
  95177. return this.getViewerById(id);
  95178. }
  95179. }
  95180. };
  95181. ViewerManager.prototype.getViewerPromiseById = function (id) {
  95182. var _this = this;
  95183. return new Promise(function (resolve, reject) {
  95184. var localViewer = _this.getViewerById(id);
  95185. if (localViewer) {
  95186. return resolve(localViewer);
  95187. }
  95188. var viewerFunction = function (viewer) {
  95189. if (viewer.getBaseId() === id) {
  95190. resolve(viewer);
  95191. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  95192. }
  95193. };
  95194. _this.onViewerAddedObservable.add(viewerFunction);
  95195. });
  95196. };
  95197. ViewerManager.prototype._onViewerAdded = function (viewer) {
  95198. this.onViewerAdded && this.onViewerAdded(viewer);
  95199. this.onViewerAddedObservable.notifyObservers(viewer);
  95200. };
  95201. ViewerManager.prototype.dispose = function () {
  95202. for (var id in this._viewers) {
  95203. this._viewers[id].dispose();
  95204. }
  95205. };
  95206. return ViewerManager;
  95207. }());
  95208. exports.ViewerManager = ViewerManager;
  95209. exports.viewerManager = new ViewerManager();
  95210. /***/ }),
  95211. /* 5 */
  95212. /***/ (function(module, exports, __webpack_require__) {
  95213. "use strict";
  95214. var __extends = (this && this.__extends) || (function () {
  95215. var extendStatics = Object.setPrototypeOf ||
  95216. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  95217. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  95218. return function (d, b) {
  95219. extendStatics(d, b);
  95220. function __() { this.constructor = d; }
  95221. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95222. };
  95223. })();
  95224. Object.defineProperty(exports, "__esModule", { value: true });
  95225. var viewer_1 = __webpack_require__(6);
  95226. var babylonjs_1 = __webpack_require__(0);
  95227. var DefaultViewer = (function (_super) {
  95228. __extends(DefaultViewer, _super);
  95229. function DefaultViewer(containerElement, initialConfiguration) {
  95230. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  95231. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  95232. _this.containerElement = containerElement;
  95233. _this._onModelLoaded = function (model) {
  95234. _this._configureTemplate(model);
  95235. var hideLoadingDelay = 500;
  95236. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  95237. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  95238. }
  95239. setTimeout(function () {
  95240. _this.hideLoadingScreen();
  95241. }, hideLoadingDelay);
  95242. return;
  95243. };
  95244. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  95245. return _this;
  95246. }
  95247. DefaultViewer.prototype._initScene = function () {
  95248. var _this = this;
  95249. return _super.prototype._initScene.call(this).then(function () {
  95250. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  95251. return _this.scene;
  95252. });
  95253. };
  95254. DefaultViewer.prototype._onTemplatesLoaded = function () {
  95255. var _this = this;
  95256. this.showLoadingScreen();
  95257. this._initNavbar();
  95258. var closeButton = document.getElementById('close-button');
  95259. if (closeButton) {
  95260. closeButton.addEventListener('pointerdown', function () {
  95261. _this.hideOverlayScreen();
  95262. });
  95263. }
  95264. return _super.prototype._onTemplatesLoaded.call(this);
  95265. };
  95266. DefaultViewer.prototype._initNavbar = function () {
  95267. var navbar = this.templateManager.getTemplate('navBar');
  95268. if (navbar) {
  95269. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  95270. var navbarShown_1 = true;
  95271. var timeoutCancel_1;
  95272. var triggerNavbar = function (show, evt) {
  95273. if (show === void 0) { show = false; }
  95274. if (!navbar || evt.button > 0)
  95275. return;
  95276. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  95277. if (show === navbarShown_1)
  95278. return;
  95279. if (show) {
  95280. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  95281. navbarShown_1 = show;
  95282. }
  95283. else {
  95284. var visibilityTimeout = 2000;
  95285. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  95286. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  95287. }
  95288. timeoutCancel_1 = setTimeout(function () {
  95289. if (navbar) {
  95290. navbar.parent.style.bottom = '-' + navbarHeight_1;
  95291. }
  95292. navbarShown_1 = show;
  95293. }, visibilityTimeout);
  95294. }
  95295. };
  95296. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  95297. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  95298. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  95299. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  95300. var viewerTemplate = this.templateManager.getTemplate('viewer');
  95301. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  95302. var triggerFullscren = function (eventData) {
  95303. if (viewerElement_1) {
  95304. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  95305. if (!fullscreenElement) {
  95306. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  95307. requestFullScreen.call(viewerElement_1);
  95308. }
  95309. else {
  95310. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  95311. exitFullscreen.call(document);
  95312. }
  95313. }
  95314. };
  95315. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  95316. }
  95317. };
  95318. DefaultViewer.prototype._prepareContainerElement = function () {
  95319. this.containerElement.style.position = 'relative';
  95320. this.containerElement.style.display = 'flex';
  95321. };
  95322. DefaultViewer.prototype._configureTemplate = function (model) {
  95323. var navbar = this.templateManager.getTemplate('navBar');
  95324. if (!navbar)
  95325. return;
  95326. var modelConfiguration = model.configuration;
  95327. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  95328. if (metadataContainer) {
  95329. if (modelConfiguration.title !== undefined) {
  95330. var element = metadataContainer.querySelector('span.model-title');
  95331. if (element) {
  95332. element.innerHTML = modelConfiguration.title;
  95333. }
  95334. }
  95335. if (modelConfiguration.subtitle !== undefined) {
  95336. var element = metadataContainer.querySelector('span.model-subtitle');
  95337. if (element) {
  95338. element.innerHTML = modelConfiguration.subtitle;
  95339. }
  95340. }
  95341. if (modelConfiguration.thumbnail !== undefined) {
  95342. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  95343. }
  95344. }
  95345. };
  95346. DefaultViewer.prototype.loadModel = function (model) {
  95347. var _this = this;
  95348. if (model === void 0) { model = this._configuration.model; }
  95349. this.showLoadingScreen();
  95350. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  95351. console.log(error);
  95352. _this.hideLoadingScreen();
  95353. _this.showOverlayScreen('error');
  95354. return Promise.reject(error);
  95355. });
  95356. };
  95357. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  95358. var _this = this;
  95359. var template = this.templateManager.getTemplate('overlay');
  95360. if (!template)
  95361. return Promise.resolve('Overlay template not found');
  95362. return template.show((function (template) {
  95363. var canvasRect = _this.containerElement.getBoundingClientRect();
  95364. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  95365. template.parent.style.display = 'flex';
  95366. template.parent.style.width = canvasRect.width + "px";
  95367. template.parent.style.height = canvasRect.height + "px";
  95368. template.parent.style.opacity = "1";
  95369. var subTemplate = _this.templateManager.getTemplate(subScreen);
  95370. if (!subTemplate) {
  95371. return Promise.reject(subScreen + ' template not found');
  95372. }
  95373. return subTemplate.show((function (template) {
  95374. template.parent.style.display = 'flex';
  95375. return Promise.resolve(template);
  95376. }));
  95377. }));
  95378. };
  95379. DefaultViewer.prototype.hideOverlayScreen = function () {
  95380. var template = this.templateManager.getTemplate('overlay');
  95381. if (!template)
  95382. return Promise.resolve('Overlay template not found');
  95383. return template.hide((function (template) {
  95384. template.parent.style.opacity = "0";
  95385. var onTransitionEnd = function () {
  95386. template.parent.removeEventListener("transitionend", onTransitionEnd);
  95387. template.parent.style.display = 'none';
  95388. };
  95389. template.parent.addEventListener("transitionend", onTransitionEnd);
  95390. var overlays = template.parent.querySelectorAll('.overlay');
  95391. if (overlays) {
  95392. for (var i = 0; i < overlays.length; ++i) {
  95393. var htmlElement = overlays.item(i);
  95394. htmlElement.style.display = 'none';
  95395. }
  95396. }
  95397. return Promise.resolve(template);
  95398. }));
  95399. };
  95400. DefaultViewer.prototype.showLoadingScreen = function () {
  95401. var _this = this;
  95402. var template = this.templateManager.getTemplate('loadingScreen');
  95403. if (!template)
  95404. return Promise.resolve('Loading Screen template not found');
  95405. return template.show((function (template) {
  95406. var canvasRect = _this.containerElement.getBoundingClientRect();
  95407. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  95408. template.parent.style.display = 'flex';
  95409. template.parent.style.width = canvasRect.width + "px";
  95410. template.parent.style.height = canvasRect.height + "px";
  95411. template.parent.style.opacity = "1";
  95412. template.parent.style.backgroundColor = "black";
  95413. return Promise.resolve(template);
  95414. }));
  95415. };
  95416. DefaultViewer.prototype.hideLoadingScreen = function () {
  95417. var template = this.templateManager.getTemplate('loadingScreen');
  95418. if (!template)
  95419. return Promise.resolve('Loading Screen template not found');
  95420. return template.hide((function (template) {
  95421. template.parent.style.opacity = "0";
  95422. var onTransitionEnd = function () {
  95423. template.parent.removeEventListener("transitionend", onTransitionEnd);
  95424. template.parent.style.display = 'none';
  95425. };
  95426. template.parent.addEventListener("transitionend", onTransitionEnd);
  95427. return Promise.resolve(template);
  95428. }));
  95429. };
  95430. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  95431. var _this = this;
  95432. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  95433. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  95434. if (this._configuration.lab && this._configuration.lab.flashlight) {
  95435. var pointerPosition = babylonjs_1.Vector3.Zero();
  95436. var lightTarget_1;
  95437. var angle = 0.5;
  95438. var exponent = Math.PI / 2;
  95439. if (typeof this._configuration.lab.flashlight === "object") {
  95440. exponent = this._configuration.lab.flashlight.exponent || exponent;
  95441. angle = this._configuration.lab.flashlight.angle || angle;
  95442. }
  95443. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  95444. if (typeof this._configuration.lab.flashlight === "object") {
  95445. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  95446. if (this._configuration.lab.flashlight.diffuse) {
  95447. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  95448. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  95449. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  95450. }
  95451. if (this._configuration.lab.flashlight.specular) {
  95452. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  95453. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  95454. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  95455. }
  95456. }
  95457. this.scene.constantlyUpdateMeshUnderPointer = true;
  95458. this.scene.onPointerObservable.add(function (eventData, eventState) {
  95459. if (eventData.type === 4 && eventData.pickInfo) {
  95460. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  95461. }
  95462. else {
  95463. lightTarget_1 = undefined;
  95464. }
  95465. });
  95466. var updateFlashlightFunction = function () {
  95467. if (_this.camera && flashlight) {
  95468. flashlight.position.copyFrom(_this.camera.position);
  95469. if (lightTarget_1) {
  95470. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  95471. }
  95472. }
  95473. };
  95474. this.scene.registerBeforeRender(updateFlashlightFunction);
  95475. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  95476. }
  95477. };
  95478. return DefaultViewer;
  95479. }(viewer_1.AbstractViewer));
  95480. exports.DefaultViewer = DefaultViewer;
  95481. /***/ }),
  95482. /* 6 */
  95483. /***/ (function(module, exports, __webpack_require__) {
  95484. "use strict";
  95485. Object.defineProperty(exports, "__esModule", { value: true });
  95486. var viewerManager_1 = __webpack_require__(4);
  95487. var templateManager_1 = __webpack_require__(23);
  95488. var loader_1 = __webpack_require__(26);
  95489. var babylonjs_1 = __webpack_require__(0);
  95490. var deepmerge = __webpack_require__(2);
  95491. var modelLoader_1 = __webpack_require__(14);
  95492. var AbstractViewer = (function () {
  95493. function AbstractViewer(containerElement, initialConfiguration) {
  95494. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  95495. var _this = this;
  95496. this.containerElement = containerElement;
  95497. this._isDisposed = false;
  95498. this._resize = function () {
  95499. if (!_this.isCanvasInDOM()) {
  95500. return;
  95501. }
  95502. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  95503. return;
  95504. }
  95505. _this.engine.resize();
  95506. };
  95507. this._render = function () {
  95508. _this.scene && _this.scene.activeCamera && _this.scene.render();
  95509. };
  95510. if (containerElement.id) {
  95511. this.baseId = containerElement.id;
  95512. }
  95513. else {
  95514. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  95515. }
  95516. this.onSceneInitObservable = new babylonjs_1.Observable();
  95517. this.onEngineInitObservable = new babylonjs_1.Observable();
  95518. this.onModelLoadedObservable = new babylonjs_1.Observable();
  95519. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  95520. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  95521. this.onInitDoneObservable = new babylonjs_1.Observable();
  95522. this.onLoaderInitObservable = new babylonjs_1.Observable();
  95523. this._registeredOnBeforeRenderFunctions = [];
  95524. this.models = [];
  95525. this.modelLoader = new modelLoader_1.ModelLoader(this);
  95526. viewerManager_1.viewerManager.addViewer(this);
  95527. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  95528. this._prepareContainerElement();
  95529. this._configurationLoader = new loader_1.ConfigurationLoader();
  95530. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  95531. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  95532. if (_this._configuration.observers) {
  95533. _this._configureObservers(_this._configuration.observers);
  95534. }
  95535. var templateConfiguration = _this._configuration.templates || {};
  95536. _this.templateManager.initTemplate(templateConfiguration);
  95537. _this.templateManager.onAllLoaded.add(function () {
  95538. var canvas = _this.templateManager.getCanvas();
  95539. if (canvas) {
  95540. _this._canvas = canvas;
  95541. }
  95542. _this._onTemplateLoaded();
  95543. });
  95544. });
  95545. }
  95546. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  95547. get: function () {
  95548. return this._hdrSupport;
  95549. },
  95550. enumerable: true,
  95551. configurable: true
  95552. });
  95553. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  95554. get: function () {
  95555. return this._canvas;
  95556. },
  95557. enumerable: true,
  95558. configurable: true
  95559. });
  95560. AbstractViewer.prototype.getBaseId = function () {
  95561. return this.baseId;
  95562. };
  95563. AbstractViewer.prototype.isCanvasInDOM = function () {
  95564. return !!this._canvas && !!this._canvas.parentElement;
  95565. };
  95566. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  95567. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  95568. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  95569. if (newConfiguration.scene) {
  95570. this._configureScene(newConfiguration.scene);
  95571. }
  95572. if (newConfiguration.optimizer) {
  95573. this._configureOptimizer(newConfiguration.optimizer);
  95574. }
  95575. if (newConfiguration.observers) {
  95576. this._configureObservers(newConfiguration.observers);
  95577. }
  95578. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  95579. this._configureModel(newConfiguration.model);
  95580. }
  95581. if (newConfiguration.lights) {
  95582. this._configureLights(newConfiguration.lights);
  95583. }
  95584. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  95585. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  95586. }
  95587. if (newConfiguration.camera) {
  95588. this._configureCamera(newConfiguration.camera);
  95589. }
  95590. };
  95591. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  95592. if (!skyboxConifguration && !groundConfiguration) {
  95593. if (this.environmentHelper) {
  95594. this.environmentHelper.dispose();
  95595. delete this.environmentHelper;
  95596. }
  95597. ;
  95598. return Promise.resolve(this.scene);
  95599. }
  95600. var options = {
  95601. createGround: !!groundConfiguration,
  95602. createSkybox: !!skyboxConifguration,
  95603. setupImageProcessing: false
  95604. };
  95605. if (groundConfiguration) {
  95606. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  95607. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  95608. if (groundSize) {
  95609. options.groundSize = groundSize;
  95610. }
  95611. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  95612. if (groundConfig.shadowLevel !== undefined) {
  95613. options.groundShadowLevel = groundConfig.shadowLevel;
  95614. }
  95615. options.enableGroundMirror = !!groundConfig.mirror;
  95616. if (groundConfig.texture) {
  95617. options.groundTexture = groundConfig.texture;
  95618. }
  95619. if (groundConfig.color) {
  95620. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  95621. }
  95622. if (groundConfig.opacity !== undefined) {
  95623. options.groundOpacity = groundConfig.opacity;
  95624. }
  95625. if (groundConfig.mirror) {
  95626. options.enableGroundMirror = true;
  95627. if (typeof groundConfig.mirror === "object") {
  95628. if (groundConfig.mirror.amount !== undefined)
  95629. options.groundMirrorAmount = groundConfig.mirror.amount;
  95630. if (groundConfig.mirror.sizeRatio !== undefined)
  95631. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  95632. if (groundConfig.mirror.blurKernel !== undefined)
  95633. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  95634. if (groundConfig.mirror.fresnelWeight !== undefined)
  95635. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  95636. if (groundConfig.mirror.fallOffDistance !== undefined)
  95637. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  95638. if (this._defaultPipelineTextureType !== undefined)
  95639. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  95640. }
  95641. }
  95642. }
  95643. var postInitSkyboxMaterial = false;
  95644. if (skyboxConifguration) {
  95645. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  95646. if (conf.material && conf.material.imageProcessingConfiguration) {
  95647. options.setupImageProcessing = false;
  95648. }
  95649. var skyboxSize = conf.scale;
  95650. if (skyboxSize) {
  95651. options.skyboxSize = skyboxSize;
  95652. }
  95653. options.sizeAuto = !options.skyboxSize;
  95654. if (conf.color) {
  95655. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  95656. }
  95657. if (conf.cubeTexture && conf.cubeTexture.url) {
  95658. if (typeof conf.cubeTexture.url === "string") {
  95659. options.skyboxTexture = conf.cubeTexture.url;
  95660. }
  95661. else {
  95662. postInitSkyboxMaterial = true;
  95663. }
  95664. }
  95665. if (conf.material && conf.material.imageProcessingConfiguration) {
  95666. postInitSkyboxMaterial = true;
  95667. }
  95668. }
  95669. options.setupImageProcessing = false;
  95670. if (!this.environmentHelper) {
  95671. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  95672. }
  95673. else {
  95674. var scene = this.environmentHelper.rootMesh.getScene();
  95675. if (scene !== this.scene) {
  95676. this.environmentHelper.dispose();
  95677. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  95678. }
  95679. else {
  95680. this.environmentHelper.updateOptions(options);
  95681. }
  95682. }
  95683. if (postInitSkyboxMaterial) {
  95684. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  95685. if (skyboxMaterial) {
  95686. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  95687. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  95688. }
  95689. }
  95690. }
  95691. };
  95692. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  95693. if (!this.scene) {
  95694. return;
  95695. }
  95696. if (sceneConfig.debug) {
  95697. this.scene.debugLayer.show();
  95698. }
  95699. else {
  95700. if (this.scene.debugLayer.isVisible()) {
  95701. this.scene.debugLayer.hide();
  95702. }
  95703. }
  95704. if (sceneConfig.clearColor) {
  95705. var cc = sceneConfig.clearColor;
  95706. var oldcc = this.scene.clearColor;
  95707. if (cc.r !== undefined) {
  95708. oldcc.r = cc.r;
  95709. }
  95710. if (cc.g !== undefined) {
  95711. oldcc.g = cc.g;
  95712. }
  95713. if (cc.b !== undefined) {
  95714. oldcc.b = cc.b;
  95715. }
  95716. if (cc.a !== undefined) {
  95717. oldcc.a = cc.a;
  95718. }
  95719. }
  95720. if (sceneConfig.imageProcessingConfiguration) {
  95721. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  95722. }
  95723. if (sceneConfig.environmentTexture) {
  95724. if (this.scene.environmentTexture) {
  95725. this.scene.environmentTexture.dispose();
  95726. }
  95727. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  95728. this.scene.environmentTexture = environmentTexture;
  95729. }
  95730. if (sceneConfig.autoRotate) {
  95731. this.camera.useAutoRotationBehavior = true;
  95732. }
  95733. };
  95734. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  95735. if (typeof optimizerConfig === 'boolean') {
  95736. if (this.sceneOptimizer) {
  95737. this.sceneOptimizer.stop();
  95738. this.sceneOptimizer.dispose();
  95739. delete this.sceneOptimizer;
  95740. }
  95741. if (optimizerConfig) {
  95742. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  95743. this.sceneOptimizer.start();
  95744. }
  95745. }
  95746. else {
  95747. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  95748. if (optimizerConfig.degradation) {
  95749. switch (optimizerConfig.degradation) {
  95750. case "low":
  95751. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  95752. break;
  95753. case "moderate":
  95754. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  95755. break;
  95756. case "hight":
  95757. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  95758. break;
  95759. }
  95760. }
  95761. if (this.sceneOptimizer) {
  95762. this.sceneOptimizer.stop();
  95763. this.sceneOptimizer.dispose();
  95764. }
  95765. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  95766. this.sceneOptimizer.start();
  95767. }
  95768. };
  95769. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  95770. if (observersConfiguration.onEngineInit) {
  95771. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  95772. }
  95773. else {
  95774. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  95775. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  95776. }
  95777. }
  95778. if (observersConfiguration.onSceneInit) {
  95779. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  95780. }
  95781. else {
  95782. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  95783. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  95784. }
  95785. }
  95786. if (observersConfiguration.onModelLoaded) {
  95787. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  95788. }
  95789. else {
  95790. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  95791. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  95792. }
  95793. }
  95794. };
  95795. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  95796. var _this = this;
  95797. var focusMeshes = model ? model.meshes : this.scene.meshes;
  95798. if (!this.scene.activeCamera) {
  95799. this.scene.createDefaultCamera(true, true, true);
  95800. this.camera = this.scene.activeCamera;
  95801. }
  95802. if (cameraConfig.position) {
  95803. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  95804. }
  95805. if (cameraConfig.rotation) {
  95806. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  95807. }
  95808. this._extendClassWithConfig(this.camera, cameraConfig);
  95809. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  95810. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  95811. if (cameraConfig.behaviors) {
  95812. for (var name_1 in cameraConfig.behaviors) {
  95813. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  95814. }
  95815. }
  95816. ;
  95817. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  95818. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  95819. });
  95820. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95821. var sceneDiagonalLenght = sceneDiagonal.length();
  95822. if (isFinite(sceneDiagonalLenght))
  95823. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  95824. };
  95825. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  95826. var _this = this;
  95827. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  95828. var focusMeshes = model ? model.meshes : this.scene.meshes;
  95829. if (!Object.keys(lightsConfiguration).length)
  95830. return;
  95831. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  95832. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  95833. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  95834. lightsAvailable.forEach(function (lName) {
  95835. if (lightsToConfigure.indexOf(lName) === -1) {
  95836. _this.scene.getLightByName(lName).dispose();
  95837. }
  95838. });
  95839. }
  95840. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  95841. var lightConfig = { type: 0 };
  95842. if (typeof lightsConfiguration[name] === 'object') {
  95843. lightConfig = lightsConfiguration[name];
  95844. }
  95845. lightConfig.name = name;
  95846. var light;
  95847. if (lightsAvailable.indexOf(name) === -1) {
  95848. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  95849. if (!constructor)
  95850. return;
  95851. light = constructor();
  95852. }
  95853. else {
  95854. light = _this.scene.getLightByName(name);
  95855. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  95856. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  95857. light.dispose();
  95858. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  95859. if (!constructor)
  95860. return;
  95861. light = constructor();
  95862. }
  95863. }
  95864. if (lightsConfiguration[name] === false) {
  95865. light.dispose();
  95866. return;
  95867. }
  95868. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  95869. light.setEnabled(enabled);
  95870. _this._extendClassWithConfig(light, lightConfig);
  95871. if (light instanceof babylonjs_1.ShadowLight) {
  95872. if (lightConfig.target) {
  95873. if (light.setDirectionToTarget) {
  95874. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  95875. light.setDirectionToTarget(target);
  95876. }
  95877. }
  95878. else if (lightConfig.direction) {
  95879. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  95880. light.direction = direction;
  95881. }
  95882. var shadowGenerator = light.getShadowGenerator();
  95883. if (lightConfig.shadowEnabled && _this._maxShadows) {
  95884. if (!shadowGenerator) {
  95885. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  95886. }
  95887. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  95888. var shadownMap = shadowGenerator.getShadowMap();
  95889. if (!shadownMap)
  95890. return;
  95891. var renderList = shadownMap.renderList;
  95892. for (var index = 0; index < focusMeshes.length; index++) {
  95893. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  95894. renderList && renderList.push(focusMeshes[index]);
  95895. }
  95896. }
  95897. }
  95898. else if (shadowGenerator) {
  95899. shadowGenerator.dispose();
  95900. }
  95901. }
  95902. });
  95903. };
  95904. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  95905. this.models.forEach(function (model) {
  95906. model.updateConfiguration(modelConfiguration);
  95907. });
  95908. };
  95909. AbstractViewer.prototype.dispose = function () {
  95910. if (this._isDisposed) {
  95911. return;
  95912. }
  95913. window.removeEventListener('resize', this._resize);
  95914. if (this.sceneOptimizer) {
  95915. this.sceneOptimizer.stop();
  95916. this.sceneOptimizer.dispose();
  95917. }
  95918. if (this.environmentHelper) {
  95919. this.environmentHelper.dispose();
  95920. }
  95921. if (this._configurationLoader) {
  95922. this._configurationLoader.dispose();
  95923. }
  95924. this.onEngineInitObservable.clear();
  95925. delete this.onEngineInitObservable;
  95926. this.onInitDoneObservable.clear();
  95927. delete this.onInitDoneObservable;
  95928. this.onLoaderInitObservable.clear();
  95929. delete this.onLoaderInitObservable;
  95930. this.onModelLoadedObservable.clear();
  95931. delete this.onModelLoadedObservable;
  95932. this.onModelLoadErrorObservable.clear();
  95933. delete this.onModelLoadErrorObservable;
  95934. this.onModelLoadProgressObservable.clear();
  95935. delete this.onModelLoadProgressObservable;
  95936. this.onSceneInitObservable.clear();
  95937. delete this.onSceneInitObservable;
  95938. if (this.scene.activeCamera) {
  95939. this.scene.activeCamera.detachControl(this.canvas);
  95940. }
  95941. this.modelLoader.dispose();
  95942. this.models.forEach(function (model) {
  95943. model.dispose();
  95944. });
  95945. this.models.length = 0;
  95946. this.scene.dispose();
  95947. this.engine.dispose();
  95948. this.templateManager.dispose();
  95949. viewerManager_1.viewerManager.removeViewer(this);
  95950. this._isDisposed = true;
  95951. };
  95952. AbstractViewer.prototype._onTemplatesLoaded = function () {
  95953. return Promise.resolve(this);
  95954. };
  95955. AbstractViewer.prototype._onTemplateLoaded = function () {
  95956. var _this = this;
  95957. return this._onTemplatesLoaded().then(function () {
  95958. var autoLoadModel = _this._configuration.model;
  95959. return _this._initEngine().then(function (engine) {
  95960. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  95961. }).then(function () {
  95962. if (autoLoadModel) {
  95963. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  95964. }
  95965. else {
  95966. return _this.scene || _this._initScene();
  95967. }
  95968. }).then(function (scene) {
  95969. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  95970. }).then(function () {
  95971. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  95972. }).catch(function (e) {
  95973. babylonjs_1.Tools.Warn(e.toString());
  95974. return _this;
  95975. });
  95976. });
  95977. };
  95978. AbstractViewer.prototype._initEngine = function () {
  95979. this._injectCustomShaders();
  95980. var canvasElement = this.templateManager.getCanvas();
  95981. if (!canvasElement) {
  95982. return Promise.reject('Canvas element not found!');
  95983. }
  95984. var config = this._configuration.engine || {};
  95985. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  95986. babylonjs_1.Database.IDBStorageEnabled = false;
  95987. if (!config.disableResize) {
  95988. window.addEventListener('resize', this._resize);
  95989. }
  95990. this.engine.runRenderLoop(this._render);
  95991. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  95992. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  95993. this.engine.setHardwareScalingLevel(scale);
  95994. }
  95995. this._handleHardwareLimitations();
  95996. return Promise.resolve(this.engine);
  95997. };
  95998. AbstractViewer.prototype._initScene = function () {
  95999. if (this.scene) {
  96000. this.scene.dispose();
  96001. }
  96002. this.scene = new babylonjs_1.Scene(this.engine);
  96003. this.scene.createDefaultLight(true);
  96004. if (this._configuration.scene) {
  96005. this._configureScene(this._configuration.scene);
  96006. if (this._configuration.optimizer) {
  96007. this._configureOptimizer(this._configuration.optimizer);
  96008. }
  96009. }
  96010. return Promise.resolve(this.scene);
  96011. };
  96012. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  96013. var _this = this;
  96014. if (clearScene === void 0) { clearScene = true; }
  96015. if (clearScene) {
  96016. this.models.forEach(function (m) { return m.dispose(); });
  96017. this.models.length = 0;
  96018. }
  96019. var model = this.modelLoader.load(modelConfig);
  96020. this.lastUsedLoader = model.loader;
  96021. model.onLoadErrorObservable.add(function (errorObject) {
  96022. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  96023. });
  96024. model.onLoadProgressObservable.add(function (progressEvent) {
  96025. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  96026. });
  96027. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  96028. model.onLoadedObservable.add(function () {
  96029. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  96030. .then(function () {
  96031. _this._configureLights(_this._configuration.lights);
  96032. if (_this._configuration.camera || !_this.scene.activeCamera) {
  96033. _this._configureCamera(_this._configuration.camera || {}, model);
  96034. }
  96035. return _this._initEnvironment(model);
  96036. }).then(function () {
  96037. _this._isLoading = false;
  96038. return model;
  96039. });
  96040. });
  96041. return model;
  96042. };
  96043. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  96044. var _this = this;
  96045. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  96046. if (clearScene === void 0) { clearScene = true; }
  96047. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  96048. if (!modelUrl) {
  96049. return Promise.reject("no model configuration found");
  96050. }
  96051. if (this._isLoading) {
  96052. return Promise.reject("another model is curently being loaded.");
  96053. }
  96054. this._isLoading = true;
  96055. if ((typeof modelConfig === 'string')) {
  96056. if (this._configuration.model && typeof this._configuration.model === 'object') {
  96057. this._configuration.model.url = modelConfig;
  96058. }
  96059. }
  96060. else {
  96061. if (this._configuration.model) {
  96062. deepmerge(this._configuration.model, modelConfig);
  96063. }
  96064. else {
  96065. this._configuration.model = modelConfig;
  96066. }
  96067. }
  96068. return Promise.resolve(this.scene).then(function (scene) {
  96069. if (!scene)
  96070. return _this._initScene();
  96071. return scene;
  96072. }).then(function () {
  96073. return new Promise(function (resolve, reject) {
  96074. return _this.initModel(modelConfig, clearScene);
  96075. });
  96076. });
  96077. };
  96078. AbstractViewer.prototype._initEnvironment = function (model) {
  96079. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  96080. return Promise.resolve(this.scene);
  96081. };
  96082. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  96083. if (enableHDR === void 0) { enableHDR = true; }
  96084. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  96085. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  96086. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  96087. this._maxShadows = 0;
  96088. }
  96089. else {
  96090. this._maxShadows = 3;
  96091. }
  96092. var caps = this.engine.getCaps();
  96093. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  96094. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  96095. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  96096. if (linearHalfFloatTargets) {
  96097. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  96098. this._shadowGeneratorBias = 0.002;
  96099. }
  96100. else if (linearFloatTargets) {
  96101. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  96102. this._shadowGeneratorBias = 0.001;
  96103. }
  96104. else {
  96105. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  96106. this._shadowGeneratorBias = 0.001;
  96107. }
  96108. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  96109. };
  96110. AbstractViewer.prototype._injectCustomShaders = function () {
  96111. var customShaders = this._configuration.customShaders;
  96112. if (!customShaders) {
  96113. return;
  96114. }
  96115. if (customShaders.shaders) {
  96116. Object.keys(customShaders.shaders).forEach(function (key) {
  96117. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  96118. });
  96119. }
  96120. if (customShaders.includes) {
  96121. Object.keys(customShaders.includes).forEach(function (key) {
  96122. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  96123. });
  96124. }
  96125. };
  96126. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  96127. var _this = this;
  96128. if (!config)
  96129. return;
  96130. Object.keys(config).forEach(function (key) {
  96131. if (key in object && typeof object[key] !== 'function') {
  96132. if (typeof object[key] === 'object') {
  96133. _this._extendClassWithConfig(object[key], config[key]);
  96134. }
  96135. else {
  96136. if (config[key] !== undefined) {
  96137. object[key] = config[key];
  96138. }
  96139. }
  96140. }
  96141. });
  96142. };
  96143. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  96144. var behavior;
  96145. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  96146. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  96147. switch (type) {
  96148. case 0:
  96149. this.camera.useAutoRotationBehavior = true;
  96150. behavior = this.camera.autoRotationBehavior;
  96151. break;
  96152. case 1:
  96153. this.camera.useBouncingBehavior = true;
  96154. behavior = this.camera.bouncingBehavior;
  96155. break;
  96156. case 2:
  96157. this.camera.useFramingBehavior = true;
  96158. behavior = this.camera.framingBehavior;
  96159. break;
  96160. default:
  96161. behavior = null;
  96162. break;
  96163. }
  96164. if (behavior) {
  96165. if (typeof behaviorConfig === "object") {
  96166. this._extendClassWithConfig(behavior, behaviorConfig);
  96167. }
  96168. }
  96169. switch (type) {
  96170. case 0:
  96171. break;
  96172. case 1:
  96173. break;
  96174. case 2:
  96175. if (config.zoomOnBoundingInfo) {
  96176. var meshes = payload;
  96177. var bounding = meshes[0].getHierarchyBoundingVectors();
  96178. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  96179. }
  96180. break;
  96181. }
  96182. };
  96183. return AbstractViewer;
  96184. }());
  96185. exports.AbstractViewer = AbstractViewer;
  96186. /***/ }),
  96187. /* 7 */
  96188. /***/ (function(module, exports) {
  96189. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  96190. /***/ }),
  96191. /* 8 */
  96192. /***/ (function(module, exports) {
  96193. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  96194. /***/ }),
  96195. /* 9 */
  96196. /***/ (function(module, exports) {
  96197. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  96198. /***/ }),
  96199. /* 10 */
  96200. /***/ (function(module, exports) {
  96201. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  96202. /***/ }),
  96203. /* 11 */
  96204. /***/ (function(module, exports) {
  96205. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}.overlay-item{width:100%;height:100%;display:none;align-items:center;justify-content:center;background-color:rgba(121,121,121,.3)}error.overlay-item{background-color:rgba(121,121,121,1)}div#close-button{position:absolute;top:10px;right:10px;width:30px;height:30px;cursor:pointer}div#close-button img{width:100%}</style> <div id=close-button> <img src={{closeImage}} alt={{closeText}}> </div> <help class=overlay-item></help> <error class=overlay-item></error> <share class=overlay-item></share>";
  96206. /***/ }),
  96207. /* 12 */
  96208. /***/ (function(module, exports) {
  96209. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  96210. /***/ }),
  96211. /* 13 */
  96212. /***/ (function(module, exports) {
  96213. module.exports = "Error loading the model";
  96214. /***/ }),
  96215. /* 14 */
  96216. /***/ (function(module, exports, __webpack_require__) {
  96217. "use strict";
  96218. Object.defineProperty(exports, "__esModule", { value: true });
  96219. var babylonjs_1 = __webpack_require__(0);
  96220. var viewerModel_1 = __webpack_require__(15);
  96221. var ModelLoader = (function () {
  96222. function ModelLoader(_viewer) {
  96223. this._viewer = _viewer;
  96224. this._disposed = false;
  96225. this._loaders = [];
  96226. this._loadId = 0;
  96227. }
  96228. ModelLoader.prototype.load = function (modelConfiguration) {
  96229. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  96230. if (!modelConfiguration.url) {
  96231. model.state = viewerModel_1.ModelState.ERROR;
  96232. babylonjs_1.Tools.Error("No URL provided");
  96233. return model;
  96234. }
  96235. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  96236. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  96237. var plugin = modelConfiguration.loader;
  96238. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  96239. meshes.forEach(function (mesh) {
  96240. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  96241. });
  96242. model.meshes = meshes;
  96243. model.particleSystems = particleSystems;
  96244. model.skeletons = skeletons;
  96245. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  96246. var animationGroup = animationGroups_1[_i];
  96247. model.addAnimationGroup(animationGroup);
  96248. }
  96249. model.initAnimations();
  96250. model.onLoadedObservable.notifyObserversWithPromise(model);
  96251. }, function (progressEvent) {
  96252. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  96253. }, function (e, m, exception) {
  96254. model.state = viewerModel_1.ModelState.ERROR;
  96255. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  96256. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  96257. }, plugin);
  96258. if (model.loader.name === "gltf") {
  96259. var gltfLoader = model.loader;
  96260. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  96261. }
  96262. model.loadId = this._loadId++;
  96263. this._loaders.push(model.loader);
  96264. return model;
  96265. };
  96266. ModelLoader.prototype.cancelLoad = function (model) {
  96267. var loader = model.loader || this._loaders[model.loadId];
  96268. if (loader && loader.name === "gltf") {
  96269. var gltfLoader = loader;
  96270. gltfLoader.dispose();
  96271. model.state = viewerModel_1.ModelState.CANCELED;
  96272. }
  96273. else {
  96274. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  96275. }
  96276. };
  96277. ModelLoader.prototype.dispose = function () {
  96278. this._loaders.forEach(function (loader) {
  96279. if (loader.name === "gltf") {
  96280. loader.dispose();
  96281. }
  96282. });
  96283. this._loaders.length = 0;
  96284. this._disposed = true;
  96285. };
  96286. return ModelLoader;
  96287. }());
  96288. exports.ModelLoader = ModelLoader;
  96289. /***/ }),
  96290. /* 15 */
  96291. /***/ (function(module, exports, __webpack_require__) {
  96292. "use strict";
  96293. Object.defineProperty(exports, "__esModule", { value: true });
  96294. var babylonjs_1 = __webpack_require__(0);
  96295. var modelAnimation_1 = __webpack_require__(16);
  96296. var deepmerge = __webpack_require__(2);
  96297. var ModelState;
  96298. (function (ModelState) {
  96299. ModelState[ModelState["INIT"] = 0] = "INIT";
  96300. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  96301. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  96302. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  96303. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  96304. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  96305. var ViewerModel = (function () {
  96306. function ViewerModel(_viewer, modelConfiguration) {
  96307. this._viewer = _viewer;
  96308. this.meshes = [];
  96309. this.particleSystems = [];
  96310. this.skeletons = [];
  96311. this.onLoadedObservable = new babylonjs_1.Observable();
  96312. this.onLoadErrorObservable = new babylonjs_1.Observable();
  96313. this.onLoadProgressObservable = new babylonjs_1.Observable();
  96314. this.onAfterConfigure = new babylonjs_1.Observable();
  96315. this.state = ModelState.INIT;
  96316. this._animations = [];
  96317. this._modelConfiguration = deepmerge({}, modelConfiguration);
  96318. this._viewer.models.push(this);
  96319. }
  96320. Object.defineProperty(ViewerModel.prototype, "configuration", {
  96321. get: function () {
  96322. return this._modelConfiguration;
  96323. },
  96324. set: function (newConfiguration) {
  96325. this._modelConfiguration = newConfiguration;
  96326. this._configureModel();
  96327. },
  96328. enumerable: true,
  96329. configurable: true
  96330. });
  96331. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  96332. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  96333. this._configureModel();
  96334. };
  96335. ViewerModel.prototype.initAnimations = function () {
  96336. var _this = this;
  96337. this._animations.forEach(function (a) {
  96338. a.dispose();
  96339. });
  96340. this._animations.length = 0;
  96341. if (this.loader.name !== 'gltf') {
  96342. this.skeletons.forEach(function (skeleton, idx) {
  96343. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  96344. skeleton.getAnimatables().forEach(function (a) {
  96345. if (a.animations[0]) {
  96346. ag.addTargetedAnimation(a.animations[0], a);
  96347. }
  96348. });
  96349. _this.addAnimationGroup(ag);
  96350. });
  96351. }
  96352. if (!this._modelConfiguration)
  96353. return;
  96354. if (this._modelConfiguration.animation) {
  96355. if (this._modelConfiguration.animation.playOnce) {
  96356. this._animations.forEach(function (a) {
  96357. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  96358. });
  96359. }
  96360. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  96361. var animationName = this._modelConfiguration.animation.autoStart === true ?
  96362. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  96363. this.playAnimation(animationName);
  96364. }
  96365. }
  96366. };
  96367. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  96368. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  96369. };
  96370. ViewerModel.prototype.getAnimations = function () {
  96371. return this._animations;
  96372. };
  96373. ViewerModel.prototype.getAnimationNames = function () {
  96374. return this._animations.map(function (a) { return a.name; });
  96375. };
  96376. ViewerModel.prototype._getAnimationByName = function (name) {
  96377. var filtered = this._animations.filter(function (a) { return a.name === name; });
  96378. if (filtered.length === 1) {
  96379. return filtered[0];
  96380. }
  96381. else {
  96382. return null;
  96383. }
  96384. };
  96385. ViewerModel.prototype.playAnimation = function (name) {
  96386. var animation = this._getAnimationByName(name);
  96387. if (animation) {
  96388. if (this.currentAnimation) {
  96389. this.currentAnimation.stop();
  96390. }
  96391. this.currentAnimation = animation;
  96392. animation.start();
  96393. return animation;
  96394. }
  96395. else {
  96396. throw new Error("animation not found - " + name);
  96397. }
  96398. };
  96399. ViewerModel.prototype._configureModel = function () {
  96400. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  96401. var updateMeshesWithNoParent = function (variable, value, param) {
  96402. meshesWithNoParent.forEach(function (mesh) {
  96403. if (param) {
  96404. mesh[variable][param] = value;
  96405. }
  96406. else {
  96407. mesh[variable] = value;
  96408. }
  96409. });
  96410. };
  96411. var updateXYZ = function (variable, configValues) {
  96412. if (configValues.x !== undefined) {
  96413. updateMeshesWithNoParent(variable, configValues.x, 'x');
  96414. }
  96415. if (configValues.y !== undefined) {
  96416. updateMeshesWithNoParent(variable, configValues.y, 'y');
  96417. }
  96418. if (configValues.z !== undefined) {
  96419. updateMeshesWithNoParent(variable, configValues.z, 'z');
  96420. }
  96421. if (configValues.w !== undefined) {
  96422. updateMeshesWithNoParent(variable, configValues.w, 'w');
  96423. }
  96424. };
  96425. if (this._modelConfiguration.position) {
  96426. updateXYZ('position', this._modelConfiguration.position);
  96427. }
  96428. if (this._modelConfiguration.rotation) {
  96429. if (this._modelConfiguration.rotation.w) {
  96430. meshesWithNoParent.forEach(function (mesh) {
  96431. if (!mesh.rotationQuaternion) {
  96432. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  96433. }
  96434. });
  96435. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  96436. }
  96437. else {
  96438. updateXYZ('rotation', this._modelConfiguration.rotation);
  96439. }
  96440. }
  96441. if (this._modelConfiguration.scaling) {
  96442. updateXYZ('scaling', this._modelConfiguration.scaling);
  96443. }
  96444. if (this._modelConfiguration.castShadow) {
  96445. this.meshes.forEach(function (mesh) {
  96446. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  96447. });
  96448. }
  96449. if (this._modelConfiguration.normalize) {
  96450. var center = false;
  96451. var unitSize = false;
  96452. var parentIndex = void 0;
  96453. if (this._modelConfiguration.normalize === true) {
  96454. center = true;
  96455. unitSize = true;
  96456. parentIndex = 0;
  96457. }
  96458. else {
  96459. center = !!this._modelConfiguration.normalize.center;
  96460. unitSize = !!this._modelConfiguration.normalize.unitSize;
  96461. parentIndex = this._modelConfiguration.normalize.parentIndex;
  96462. }
  96463. var meshesToNormalize = [];
  96464. if (parentIndex !== undefined) {
  96465. meshesToNormalize.push(this.meshes[parentIndex]);
  96466. }
  96467. else {
  96468. meshesToNormalize = meshesWithNoParent;
  96469. }
  96470. if (unitSize) {
  96471. meshesToNormalize.forEach(function (mesh) {
  96472. mesh.normalizeToUnitCube(true);
  96473. mesh.computeWorldMatrix(true);
  96474. });
  96475. }
  96476. if (center) {
  96477. meshesToNormalize.forEach(function (mesh) {
  96478. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  96479. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  96480. var halfSizeVec = sizeVec.scale(0.5);
  96481. var center = boundingInfo.min.add(halfSizeVec);
  96482. mesh.position = center.scale(-1);
  96483. mesh.position.y += halfSizeVec.y;
  96484. mesh.computeWorldMatrix(true);
  96485. });
  96486. }
  96487. }
  96488. this.onAfterConfigure.notifyObservers(this);
  96489. };
  96490. ViewerModel.prototype.dispose = function () {
  96491. this.onAfterConfigure.clear();
  96492. this.onLoadedObservable.clear();
  96493. this.onLoadErrorObservable.clear();
  96494. this.onLoadProgressObservable.clear();
  96495. if (this.loader && this.loader.name === "gltf") {
  96496. this.loader.dispose();
  96497. }
  96498. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  96499. this.particleSystems.length = 0;
  96500. this.skeletons.forEach(function (s) { return s.dispose(); });
  96501. this.skeletons.length = 0;
  96502. this._animations.forEach(function (ag) { return ag.dispose(); });
  96503. this._animations.length = 0;
  96504. this.meshes.forEach(function (m) { return m.dispose(); });
  96505. this.meshes.length = 0;
  96506. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  96507. };
  96508. return ViewerModel;
  96509. }());
  96510. exports.ViewerModel = ViewerModel;
  96511. /***/ }),
  96512. /* 16 */
  96513. /***/ (function(module, exports, __webpack_require__) {
  96514. "use strict";
  96515. Object.defineProperty(exports, "__esModule", { value: true });
  96516. var AnimationPlayMode;
  96517. (function (AnimationPlayMode) {
  96518. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  96519. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  96520. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  96521. var AnimationState;
  96522. (function (AnimationState) {
  96523. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  96524. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  96525. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  96526. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  96527. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  96528. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  96529. var GroupModelAnimation = (function () {
  96530. function GroupModelAnimation(_animationGroup) {
  96531. var _this = this;
  96532. this._animationGroup = _animationGroup;
  96533. this._state = AnimationState.INIT;
  96534. this._playMode = AnimationPlayMode.LOOP;
  96535. this._animationGroup.onAnimationEndObservable.add(function () {
  96536. _this.stop();
  96537. _this._state = AnimationState.ENDED;
  96538. });
  96539. }
  96540. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  96541. get: function () {
  96542. return this._animationGroup.name;
  96543. },
  96544. enumerable: true,
  96545. configurable: true
  96546. });
  96547. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  96548. get: function () {
  96549. return this._state;
  96550. },
  96551. enumerable: true,
  96552. configurable: true
  96553. });
  96554. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  96555. get: function () {
  96556. return this._animationGroup.speedRatio;
  96557. },
  96558. set: function (value) {
  96559. this._animationGroup.speedRatio = value;
  96560. },
  96561. enumerable: true,
  96562. configurable: true
  96563. });
  96564. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  96565. get: function () {
  96566. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  96567. var keys = ta.animation.getKeys();
  96568. return keys[keys.length - 1].frame;
  96569. });
  96570. return Math.max.apply(null, animationFrames);
  96571. },
  96572. enumerable: true,
  96573. configurable: true
  96574. });
  96575. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  96576. get: function () {
  96577. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  96578. var animatable = this._animationGroup.animatables[i];
  96579. var animations = animatable.getAnimations();
  96580. if (!animations || !animations.length) {
  96581. continue;
  96582. }
  96583. for (var idx = 0; idx < animations.length; ++idx) {
  96584. if (animations[idx].currentFrame) {
  96585. return animations[idx].currentFrame;
  96586. }
  96587. }
  96588. }
  96589. return 0;
  96590. },
  96591. enumerable: true,
  96592. configurable: true
  96593. });
  96594. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  96595. get: function () {
  96596. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  96597. var animatable = this._animationGroup.animatables[i];
  96598. var animations = animatable.getAnimations();
  96599. if (!animations || !animations.length) {
  96600. continue;
  96601. }
  96602. for (var idx = 0; idx < animations.length; ++idx) {
  96603. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  96604. return animations[idx].animation.framePerSecond;
  96605. }
  96606. }
  96607. }
  96608. return 0;
  96609. },
  96610. enumerable: true,
  96611. configurable: true
  96612. });
  96613. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  96614. get: function () {
  96615. return this._playMode;
  96616. },
  96617. set: function (value) {
  96618. if (value === this._playMode) {
  96619. return;
  96620. }
  96621. this._playMode = value;
  96622. if (this.state === AnimationState.PLAYING) {
  96623. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  96624. }
  96625. else {
  96626. this._animationGroup.reset();
  96627. this._state = AnimationState.INIT;
  96628. }
  96629. },
  96630. enumerable: true,
  96631. configurable: true
  96632. });
  96633. GroupModelAnimation.prototype.reset = function () {
  96634. this._animationGroup.reset();
  96635. };
  96636. GroupModelAnimation.prototype.restart = function () {
  96637. this._animationGroup.restart();
  96638. };
  96639. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  96640. this._animationGroup['_animatables'].forEach(function (a) {
  96641. a.goToFrame(frameNumber);
  96642. });
  96643. };
  96644. GroupModelAnimation.prototype.start = function () {
  96645. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  96646. if (this._animationGroup.isStarted) {
  96647. this._state = AnimationState.PLAYING;
  96648. }
  96649. };
  96650. GroupModelAnimation.prototype.pause = function () {
  96651. this._animationGroup.pause();
  96652. this._state = AnimationState.PAUSED;
  96653. };
  96654. GroupModelAnimation.prototype.stop = function () {
  96655. this._animationGroup.stop();
  96656. if (!this._animationGroup.isStarted) {
  96657. this._state = AnimationState.STOPPED;
  96658. }
  96659. };
  96660. GroupModelAnimation.prototype.dispose = function () {
  96661. this._animationGroup.dispose();
  96662. };
  96663. return GroupModelAnimation;
  96664. }());
  96665. exports.GroupModelAnimation = GroupModelAnimation;
  96666. /***/ }),
  96667. /* 17 */
  96668. /***/ (function(module, exports, __webpack_require__) {
  96669. module.exports = __webpack_require__(18);
  96670. /***/ }),
  96671. /* 18 */
  96672. /***/ (function(module, exports, __webpack_require__) {
  96673. "use strict";
  96674. Object.defineProperty(exports, "__esModule", { value: true });
  96675. var mappers_1 = __webpack_require__(1);
  96676. exports.mapperManager = mappers_1.mapperManager;
  96677. var viewerManager_1 = __webpack_require__(4);
  96678. exports.viewerManager = viewerManager_1.viewerManager;
  96679. var defaultViewer_1 = __webpack_require__(5);
  96680. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  96681. var viewer_1 = __webpack_require__(6);
  96682. exports.AbstractViewer = viewer_1.AbstractViewer;
  96683. var modelLoader_1 = __webpack_require__(14);
  96684. exports.ModelLoader = modelLoader_1.ModelLoader;
  96685. var viewerModel_1 = __webpack_require__(15);
  96686. exports.ViewerModel = viewerModel_1.ViewerModel;
  96687. exports.ModelState = viewerModel_1.ModelState;
  96688. var modelAnimation_1 = __webpack_require__(16);
  96689. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  96690. exports.AnimationState = modelAnimation_1.AnimationState;
  96691. var babylonjs_1 = __webpack_require__(0);
  96692. __webpack_require__(34);
  96693. __webpack_require__(35);
  96694. var initializer_1 = __webpack_require__(36);
  96695. exports.InitTags = initializer_1.InitTags;
  96696. babylonjs_1.PromisePolyfill.Apply();
  96697. exports.disableInit = false;
  96698. document.addEventListener("DOMContentLoaded", init);
  96699. function init(event) {
  96700. document.removeEventListener("DOMContentLoaded", init);
  96701. if (exports.disableInit)
  96702. return;
  96703. initializer_1.InitTags();
  96704. }
  96705. function disposeAll() {
  96706. viewerManager_1.viewerManager.dispose();
  96707. mappers_1.mapperManager.dispose();
  96708. }
  96709. exports.disposeAll = disposeAll;
  96710. /***/ }),
  96711. /* 19 */
  96712. /***/ (function(module, exports) {
  96713. var g;
  96714. // This works in non-strict mode
  96715. g = (function() {
  96716. return this;
  96717. })();
  96718. try {
  96719. // This works if eval is allowed (see CSP)
  96720. g = g || Function("return this")() || (1,eval)("this");
  96721. } catch(e) {
  96722. // This works if the window reference is available
  96723. if(typeof window === "object")
  96724. g = window;
  96725. }
  96726. // g can still be undefined, but nothing to do about it...
  96727. // We return undefined, instead of nothing here, so it's
  96728. // easier to handle this case. if(!global) { ...}
  96729. module.exports = g;
  96730. /***/ }),
  96731. /* 20 */
  96732. /***/ (function(module, exports) {
  96733. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  96734. module.exports = CANNON;
  96735. /***/ }),
  96736. /* 21 */
  96737. /***/ (function(module, exports) {
  96738. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  96739. module.exports = OIMO;
  96740. /***/ }),
  96741. /* 22 */
  96742. /***/ (function(module, exports) {
  96743. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  96744. module.exports = earcut;
  96745. /***/ }),
  96746. /* 23 */
  96747. /***/ (function(module, exports, __webpack_require__) {
  96748. "use strict";
  96749. Object.defineProperty(exports, "__esModule", { value: true });
  96750. var babylonjs_1 = __webpack_require__(0);
  96751. var helper_1 = __webpack_require__(3);
  96752. var TemplateManager = (function () {
  96753. function TemplateManager(containerElement) {
  96754. this.containerElement = containerElement;
  96755. this.templates = {};
  96756. this.onTemplateInit = new babylonjs_1.Observable();
  96757. this.onTemplateLoaded = new babylonjs_1.Observable();
  96758. this.onTemplateStateChange = new babylonjs_1.Observable();
  96759. this.onAllLoaded = new babylonjs_1.Observable();
  96760. this.onEventTriggered = new babylonjs_1.Observable();
  96761. this.eventManager = new eventManager_1.EventManager(this);
  96762. }
  96763. TemplateManager.prototype.initTemplate = function (templates) {
  96764. var _this = this;
  96765. var internalInit = function (dependencyMap, name, parentTemplate) {
  96766. var template = _this.templates[name];
  96767. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  96768. return internalInit(dependencyMap[childName], childName, template);
  96769. });
  96770. var addToParent = function () {
  96771. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  96772. template.appendTo(containingElement);
  96773. _this._checkLoadedState();
  96774. };
  96775. if (parentTemplate && !parentTemplate.parent) {
  96776. parentTemplate.onAppended.add(function () {
  96777. addToParent();
  96778. });
  96779. }
  96780. else {
  96781. addToParent();
  96782. }
  96783. return template;
  96784. };
  96785. return this._buildHTMLTree(templates).then(function (htmlTree) {
  96786. if (_this.templates['main']) {
  96787. internalInit(htmlTree, 'main');
  96788. }
  96789. else {
  96790. _this._checkLoadedState();
  96791. }
  96792. return;
  96793. });
  96794. };
  96795. TemplateManager.prototype._buildHTMLTree = function (templates) {
  96796. var _this = this;
  96797. var promises = Object.keys(templates).map(function (name) {
  96798. if (!templates[name])
  96799. return Promise.resolve(false);
  96800. var template = new Template(name, templates[name]);
  96801. template.onLoaded.add(function () {
  96802. _this.onTemplateLoaded.notifyObservers(template);
  96803. });
  96804. template.onStateChange.add(function () {
  96805. _this.onTemplateStateChange.notifyObservers(template);
  96806. });
  96807. _this.onTemplateInit.notifyObservers(template);
  96808. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  96809. _this.templates[name] = template;
  96810. return template.initPromise;
  96811. });
  96812. return Promise.all(promises).then(function () {
  96813. var templateStructure = {};
  96814. var buildTree = function (parentObject, name) {
  96815. _this.templates[name].isInHtmlTree = true;
  96816. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  96817. childNodes.forEach(function (element) {
  96818. parentObject[element] = {};
  96819. buildTree(parentObject[element], element);
  96820. });
  96821. };
  96822. if (_this.templates['main']) {
  96823. buildTree(templateStructure, "main");
  96824. }
  96825. return templateStructure;
  96826. });
  96827. };
  96828. TemplateManager.prototype.getCanvas = function () {
  96829. return this.containerElement.querySelector('canvas');
  96830. };
  96831. TemplateManager.prototype.getTemplate = function (name) {
  96832. return this.templates[name];
  96833. };
  96834. TemplateManager.prototype._checkLoadedState = function () {
  96835. var _this = this;
  96836. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  96837. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  96838. });
  96839. if (done) {
  96840. this.onAllLoaded.notifyObservers(this);
  96841. }
  96842. };
  96843. TemplateManager.prototype.dispose = function () {
  96844. var _this = this;
  96845. Object.keys(this.templates).forEach(function (template) {
  96846. _this.templates[template].dispose();
  96847. });
  96848. this.templates = {};
  96849. this.eventManager.dispose();
  96850. this.onTemplateInit.clear();
  96851. this.onAllLoaded.clear();
  96852. this.onEventTriggered.clear();
  96853. this.onTemplateLoaded.clear();
  96854. this.onTemplateStateChange.clear();
  96855. };
  96856. return TemplateManager;
  96857. }());
  96858. exports.TemplateManager = TemplateManager;
  96859. var Handlebars = __webpack_require__(24);
  96860. var eventManager_1 = __webpack_require__(25);
  96861. Handlebars.registerHelper('eachInMap', function (map, block) {
  96862. var out = '';
  96863. Object.keys(map).map(function (prop) {
  96864. var data = map[prop];
  96865. if (typeof data === 'object') {
  96866. data.id = data.id || prop;
  96867. out += block.fn(data);
  96868. }
  96869. else {
  96870. out += block.fn({ id: prop, value: data });
  96871. }
  96872. });
  96873. return out;
  96874. });
  96875. var Template = (function () {
  96876. function Template(name, _configuration) {
  96877. var _this = this;
  96878. this.name = name;
  96879. this._configuration = _configuration;
  96880. this.onLoaded = new babylonjs_1.Observable();
  96881. this.onAppended = new babylonjs_1.Observable();
  96882. this.onStateChange = new babylonjs_1.Observable();
  96883. this.onEventTriggered = new babylonjs_1.Observable();
  96884. this.loadRequests = [];
  96885. this.isLoaded = false;
  96886. this.isShown = false;
  96887. this.isInHtmlTree = false;
  96888. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  96889. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  96890. if (htmlTemplate) {
  96891. _this._htmlTemplate = htmlTemplate;
  96892. var compiledTemplate = Handlebars.compile(htmlTemplate);
  96893. var config = _this._configuration.params || {};
  96894. var rawHtml = compiledTemplate(config);
  96895. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  96896. _this.isLoaded = true;
  96897. _this.isShown = true;
  96898. _this.onLoaded.notifyObservers(_this);
  96899. }
  96900. return _this;
  96901. });
  96902. }
  96903. Template.prototype.updateParams = function (params) {
  96904. this._configuration.params = params;
  96905. if (this.isLoaded) {
  96906. this.dispose();
  96907. }
  96908. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  96909. var config = this._configuration.params || {};
  96910. var rawHtml = compiledTemplate(config);
  96911. this._fragment = document.createRange().createContextualFragment(rawHtml);
  96912. if (this.parent) {
  96913. this.appendTo(this.parent, true);
  96914. }
  96915. };
  96916. Object.defineProperty(Template.prototype, "configuration", {
  96917. get: function () {
  96918. return this._configuration;
  96919. },
  96920. enumerable: true,
  96921. configurable: true
  96922. });
  96923. Template.prototype.getChildElements = function () {
  96924. var childrenArray = [];
  96925. var children = this._fragment.children;
  96926. if (!children) {
  96927. children = this._fragment.querySelectorAll('*');
  96928. }
  96929. for (var i = 0; i < children.length; ++i) {
  96930. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  96931. }
  96932. return childrenArray;
  96933. };
  96934. Template.prototype.appendTo = function (parent, forceRemove) {
  96935. var _this = this;
  96936. if (this.parent) {
  96937. if (forceRemove) {
  96938. this.parent.removeChild(this._fragment);
  96939. }
  96940. else {
  96941. return;
  96942. }
  96943. }
  96944. this.parent = parent;
  96945. if (this._configuration.id) {
  96946. this.parent.id = this._configuration.id;
  96947. }
  96948. this._fragment = this.parent.appendChild(this._fragment);
  96949. setTimeout(function () {
  96950. _this._registerEvents();
  96951. _this.onAppended.notifyObservers(_this);
  96952. });
  96953. };
  96954. Template.prototype.show = function (visibilityFunction) {
  96955. var _this = this;
  96956. if (this._isHiding)
  96957. return Promise.resolve(this);
  96958. return Promise.resolve().then(function () {
  96959. _this._isShowing = true;
  96960. if (visibilityFunction) {
  96961. return visibilityFunction(_this);
  96962. }
  96963. else {
  96964. _this.parent.style.display = 'flex';
  96965. return _this;
  96966. }
  96967. }).then(function () {
  96968. _this.isShown = true;
  96969. _this._isShowing = false;
  96970. _this.onStateChange.notifyObservers(_this);
  96971. return _this;
  96972. });
  96973. };
  96974. Template.prototype.hide = function (visibilityFunction) {
  96975. var _this = this;
  96976. if (this._isShowing)
  96977. return Promise.resolve(this);
  96978. return Promise.resolve().then(function () {
  96979. _this._isHiding = true;
  96980. if (visibilityFunction) {
  96981. return visibilityFunction(_this);
  96982. }
  96983. else {
  96984. _this.parent.style.display = 'hide';
  96985. return _this;
  96986. }
  96987. }).then(function () {
  96988. _this.isShown = false;
  96989. _this._isHiding = false;
  96990. _this.onStateChange.notifyObservers(_this);
  96991. return _this;
  96992. });
  96993. };
  96994. Template.prototype.dispose = function () {
  96995. this.onAppended.clear();
  96996. this.onEventTriggered.clear();
  96997. this.onLoaded.clear();
  96998. this.onStateChange.clear();
  96999. this.isLoaded = false;
  97000. try {
  97001. this.parent.removeChild(this._fragment);
  97002. }
  97003. catch (e) {
  97004. }
  97005. this.loadRequests.forEach(function (request) {
  97006. request.abort();
  97007. });
  97008. if (this._registeredEvents) {
  97009. this._registeredEvents.forEach(function (evt) {
  97010. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  97011. });
  97012. }
  97013. delete this._fragment;
  97014. };
  97015. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  97016. var _this = this;
  97017. if (!templateConfig) {
  97018. return Promise.reject('No templateConfig provided');
  97019. }
  97020. else if (templateConfig.html !== undefined) {
  97021. return Promise.resolve(templateConfig.html);
  97022. }
  97023. else {
  97024. var location_1 = this._getTemplateLocation(templateConfig);
  97025. if (helper_1.isUrl(location_1)) {
  97026. return new Promise(function (resolve, reject) {
  97027. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  97028. resolve(data);
  97029. }, undefined, undefined, false, function (request, error) {
  97030. reject(error);
  97031. });
  97032. _this.loadRequests.push(fileRequest);
  97033. });
  97034. }
  97035. else {
  97036. location_1 = location_1.replace('#', '');
  97037. var element = document.getElementById(location_1);
  97038. if (element) {
  97039. return Promise.resolve(element.innerHTML);
  97040. }
  97041. else {
  97042. return Promise.reject('Template ID not found');
  97043. }
  97044. }
  97045. }
  97046. };
  97047. Template.prototype._registerEvents = function () {
  97048. var _this = this;
  97049. this._registeredEvents = this._registeredEvents || [];
  97050. if (this._registeredEvents.length) {
  97051. this._registeredEvents.forEach(function (evt) {
  97052. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  97053. });
  97054. }
  97055. if (this._configuration.events) {
  97056. var _loop_1 = function (eventName) {
  97057. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  97058. var functionToFire_1 = function (selector, event) {
  97059. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  97060. };
  97061. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  97062. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  97063. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  97064. this_1._registeredEvents.push({
  97065. htmlElement: this_1.parent,
  97066. eventName: eventName,
  97067. function: binding
  97068. });
  97069. }
  97070. else if (typeof this_1._configuration.events[eventName] === 'object') {
  97071. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  97072. var event_1 = this_1._configuration.events[eventName] || {};
  97073. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  97074. if (selector && selector.indexOf('#') !== 0) {
  97075. selector = '#' + selector;
  97076. }
  97077. var htmlElement = _this.parent.querySelector(selector);
  97078. if (htmlElement) {
  97079. var binding = functionToFire_1.bind(_this, selector);
  97080. htmlElement.addEventListener(eventName, binding, false);
  97081. _this._registeredEvents.push({
  97082. htmlElement: htmlElement,
  97083. eventName: eventName,
  97084. function: binding
  97085. });
  97086. }
  97087. });
  97088. }
  97089. }
  97090. };
  97091. var this_1 = this;
  97092. for (var eventName in this._configuration.events) {
  97093. _loop_1(eventName);
  97094. }
  97095. }
  97096. };
  97097. Template.prototype._getTemplateLocation = function (templateConfig) {
  97098. if (!templateConfig || typeof templateConfig === 'string') {
  97099. return templateConfig;
  97100. }
  97101. else {
  97102. return templateConfig.location;
  97103. }
  97104. };
  97105. return Template;
  97106. }());
  97107. exports.Template = Template;
  97108. /***/ }),
  97109. /* 24 */
  97110. /***/ (function(module, exports, __webpack_require__) {
  97111. /**!
  97112. @license
  97113. handlebars v4.0.11
  97114. Copyright (C) 2011-2017 by Yehuda Katz
  97115. Permission is hereby granted, free of charge, to any person obtaining a copy
  97116. of this software and associated documentation files (the "Software"), to deal
  97117. in the Software without restriction, including without limitation the rights
  97118. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  97119. copies of the Software, and to permit persons to whom the Software is
  97120. furnished to do so, subject to the following conditions:
  97121. The above copyright notice and this permission notice shall be included in
  97122. all copies or substantial portions of the Software.
  97123. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  97124. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  97125. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  97126. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  97127. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  97128. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  97129. THE SOFTWARE.
  97130. */
  97131. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  97132. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  97133. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  97134. /***/ }),
  97135. /* 25 */
  97136. /***/ (function(module, exports, __webpack_require__) {
  97137. "use strict";
  97138. Object.defineProperty(exports, "__esModule", { value: true });
  97139. var EventManager = (function () {
  97140. function EventManager(_templateManager) {
  97141. var _this = this;
  97142. this._templateManager = _templateManager;
  97143. this._callbacksContainer = {};
  97144. this._templateManager.onEventTriggered.add(function (eventData) {
  97145. _this._eventTriggered(eventData);
  97146. });
  97147. }
  97148. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  97149. if (!this._callbacksContainer[templateName]) {
  97150. this._callbacksContainer[templateName] = [];
  97151. }
  97152. this._callbacksContainer[templateName].push({
  97153. eventType: eventType,
  97154. callback: callback
  97155. });
  97156. };
  97157. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  97158. var callbackDefs = this._callbacksContainer[templateName] || [];
  97159. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  97160. };
  97161. EventManager.prototype._eventTriggered = function (data) {
  97162. var templateName = data.template.name;
  97163. var eventType = data.event.type;
  97164. var selector = data.selector;
  97165. var callbackDefs = this._callbacksContainer[templateName] || [];
  97166. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  97167. callbackDef.callback(data);
  97168. });
  97169. };
  97170. EventManager.prototype.dispose = function () {
  97171. this._callbacksContainer = {};
  97172. };
  97173. return EventManager;
  97174. }());
  97175. exports.EventManager = EventManager;
  97176. /***/ }),
  97177. /* 26 */
  97178. /***/ (function(module, exports, __webpack_require__) {
  97179. "use strict";
  97180. Object.defineProperty(exports, "__esModule", { value: true });
  97181. var mappers_1 = __webpack_require__(1);
  97182. var types_1 = __webpack_require__(27);
  97183. var deepmerge = __webpack_require__(2);
  97184. var babylonjs_1 = __webpack_require__(0);
  97185. var ConfigurationLoader = (function () {
  97186. function ConfigurationLoader(_enableCache) {
  97187. if (_enableCache === void 0) { _enableCache = false; }
  97188. this._enableCache = _enableCache;
  97189. this._configurationCache = {};
  97190. this._loadRequests = [];
  97191. }
  97192. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  97193. var _this = this;
  97194. if (initConfig === void 0) { initConfig = {}; }
  97195. var loadedConfig = deepmerge({}, initConfig);
  97196. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  97197. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  97198. if (loadedConfig.configuration) {
  97199. var mapperType_1 = "json";
  97200. return Promise.resolve().then(function () {
  97201. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  97202. var url = '';
  97203. if (typeof loadedConfig.configuration === "string") {
  97204. url = loadedConfig.configuration;
  97205. }
  97206. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  97207. url = loadedConfig.configuration.url;
  97208. var type = loadedConfig.configuration.mapper;
  97209. if (!type) {
  97210. type = loadedConfig.configuration.url.split('.').pop();
  97211. }
  97212. mapperType_1 = type || mapperType_1;
  97213. }
  97214. return _this._loadFile(url);
  97215. }
  97216. else {
  97217. if (typeof loadedConfig.configuration === "object") {
  97218. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  97219. return loadedConfig.configuration.payload || {};
  97220. }
  97221. return {};
  97222. }
  97223. }).then(function (data) {
  97224. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  97225. var parsed = mapper.map(data);
  97226. var merged = deepmerge(loadedConfig, parsed);
  97227. if (callback)
  97228. callback(merged);
  97229. return merged;
  97230. });
  97231. }
  97232. else {
  97233. if (callback)
  97234. callback(loadedConfig);
  97235. return Promise.resolve(loadedConfig);
  97236. }
  97237. };
  97238. ConfigurationLoader.prototype.dispose = function () {
  97239. this._loadRequests.forEach(function (request) {
  97240. request.abort();
  97241. });
  97242. this._loadRequests.length = 0;
  97243. };
  97244. ConfigurationLoader.prototype._loadFile = function (url) {
  97245. var _this = this;
  97246. var cacheReference = this._configurationCache;
  97247. if (this._enableCache && cacheReference[url]) {
  97248. return Promise.resolve(cacheReference[url]);
  97249. }
  97250. return new Promise(function (resolve, reject) {
  97251. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  97252. var idx = _this._loadRequests.indexOf(fileRequest);
  97253. if (idx !== -1)
  97254. _this._loadRequests.splice(idx, 1);
  97255. if (_this._enableCache)
  97256. cacheReference[url] = result;
  97257. resolve(result);
  97258. }, undefined, undefined, false, function (request, error) {
  97259. var idx = _this._loadRequests.indexOf(fileRequest);
  97260. if (idx !== -1)
  97261. _this._loadRequests.splice(idx, 1);
  97262. reject(error);
  97263. });
  97264. _this._loadRequests.push(fileRequest);
  97265. });
  97266. };
  97267. return ConfigurationLoader;
  97268. }());
  97269. exports.ConfigurationLoader = ConfigurationLoader;
  97270. /***/ }),
  97271. /* 27 */
  97272. /***/ (function(module, exports, __webpack_require__) {
  97273. "use strict";
  97274. Object.defineProperty(exports, "__esModule", { value: true });
  97275. var minimal_1 = __webpack_require__(28);
  97276. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  97277. var default_1 = __webpack_require__(29);
  97278. exports.defaultConfiguration = default_1.defaultConfiguration;
  97279. var getConfigurationType = function (type) {
  97280. switch (type) {
  97281. case 'default':
  97282. return default_1.defaultConfiguration;
  97283. case 'minimal':
  97284. return minimal_1.minimalConfiguration;
  97285. case 'none':
  97286. return {};
  97287. default:
  97288. return default_1.defaultConfiguration;
  97289. }
  97290. };
  97291. exports.getConfigurationType = getConfigurationType;
  97292. /***/ }),
  97293. /* 28 */
  97294. /***/ (function(module, exports, __webpack_require__) {
  97295. "use strict";
  97296. Object.defineProperty(exports, "__esModule", { value: true });
  97297. exports.minimalConfiguration = {
  97298. version: "0.1",
  97299. templates: {
  97300. main: {
  97301. html: __webpack_require__(7)
  97302. },
  97303. loadingScreen: {
  97304. html: __webpack_require__(8),
  97305. params: {
  97306. backgroundColor: "#000000",
  97307. loadingImage: __webpack_require__(9)
  97308. }
  97309. },
  97310. viewer: {
  97311. html: __webpack_require__(10),
  97312. },
  97313. overlay: {
  97314. html: __webpack_require__(11),
  97315. params: {
  97316. closeImage: __webpack_require__(12),
  97317. closeText: 'Close'
  97318. }
  97319. },
  97320. error: {
  97321. html: __webpack_require__(13)
  97322. }
  97323. },
  97324. engine: {
  97325. antialiasing: true
  97326. }
  97327. };
  97328. /***/ }),
  97329. /* 29 */
  97330. /***/ (function(module, exports, __webpack_require__) {
  97331. "use strict";
  97332. Object.defineProperty(exports, "__esModule", { value: true });
  97333. exports.defaultConfiguration = {
  97334. version: "3.2.0-alpha4",
  97335. templates: {
  97336. main: {
  97337. html: __webpack_require__(7)
  97338. },
  97339. loadingScreen: {
  97340. html: __webpack_require__(8),
  97341. params: {
  97342. backgroundColor: "#000000",
  97343. loadingImage: __webpack_require__(9)
  97344. }
  97345. },
  97346. viewer: {
  97347. html: __webpack_require__(10),
  97348. events: {
  97349. pointerout: true,
  97350. pointerdown: true,
  97351. pointerup: true
  97352. }
  97353. },
  97354. navBar: {
  97355. html: __webpack_require__(30),
  97356. params: {
  97357. buttons: {
  97358. "fullscreen-button": {
  97359. altText: "Fullscreen",
  97360. image: __webpack_require__(31)
  97361. }
  97362. },
  97363. visibilityTimeout: 2000
  97364. },
  97365. events: {
  97366. pointerdown: { 'fullscreen-button': true },
  97367. pointerover: true
  97368. }
  97369. },
  97370. overlay: {
  97371. html: __webpack_require__(11),
  97372. params: {
  97373. closeImage: __webpack_require__(12),
  97374. closeText: 'Close'
  97375. }
  97376. },
  97377. help: {
  97378. html: __webpack_require__(32)
  97379. },
  97380. share: {
  97381. html: __webpack_require__(33)
  97382. },
  97383. error: {
  97384. html: __webpack_require__(13)
  97385. }
  97386. },
  97387. camera: {
  97388. behaviors: {
  97389. autoRotate: 0,
  97390. framing: {
  97391. type: 2,
  97392. zoomOnBoundingInfo: true,
  97393. zoomStopsAnimation: false
  97394. }
  97395. }
  97396. },
  97397. skybox: {
  97398. pbr: true,
  97399. blur: 0.7,
  97400. infiniteDIstance: false,
  97401. },
  97402. ground: true,
  97403. engine: {
  97404. antialiasing: true
  97405. },
  97406. scene: {
  97407. imageProcessingConfiguration: {
  97408. exposure: 1.4,
  97409. contrast: 1.66,
  97410. toneMappingEnabled: true
  97411. }
  97412. }
  97413. };
  97414. /***/ }),
  97415. /* 30 */
  97416. /***/ (function(module, exports) {
  97417. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  97418. /***/ }),
  97419. /* 31 */
  97420. /***/ (function(module, exports) {
  97421. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  97422. /***/ }),
  97423. /* 32 */
  97424. /***/ (function(module, exports) {
  97425. module.exports = "HELP";
  97426. /***/ }),
  97427. /* 33 */
  97428. /***/ (function(module, exports) {
  97429. module.exports = "SHARE";
  97430. /***/ }),
  97431. /* 34 */
  97432. /***/ (function(module, exports, __webpack_require__) {
  97433. 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};
  97434. 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)}}();
  97435. (function universalModuleDefinition(root, factory) {
  97436. var amdDependencies = [];
  97437. var BABYLON = root.BABYLON || this.BABYLON;
  97438. if(true) {
  97439. BABYLON = BABYLON || __webpack_require__(0);
  97440. module.exports = factory(BABYLON);
  97441. } else if(typeof define === 'function' && define.amd) {
  97442. amdDependencies.push("babylonjs");
  97443. define("babylonjs-loaders", amdDependencies, factory);
  97444. } else if(typeof exports === 'object') {
  97445. BABYLON = BABYLON || require("babylonjs");
  97446. exports["babylonjs-loaders"] = factory(BABYLON);
  97447. } else {
  97448. root["BABYLON"] = factory(BABYLON);
  97449. }
  97450. })(this, function(BABYLON) {
  97451. BABYLON = BABYLON || this.BABYLON;
  97452. "use strict";
  97453. var BABYLON;
  97454. (function (BABYLON) {
  97455. var STLFileLoader = /** @class */ (function () {
  97456. function STLFileLoader() {
  97457. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  97458. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  97459. 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;
  97460. 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;
  97461. this.name = "stl";
  97462. // force data to come in as an ArrayBuffer
  97463. // we'll convert to string if it looks like it's an ASCII .stl
  97464. this.extensions = {
  97465. ".stl": { isBinary: true },
  97466. };
  97467. }
  97468. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  97469. var matches;
  97470. if (this.isBinary(data)) {
  97471. // binary .stl
  97472. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  97473. this.parseBinary(babylonMesh, data);
  97474. if (meshes) {
  97475. meshes.push(babylonMesh);
  97476. }
  97477. return true;
  97478. }
  97479. // ASCII .stl
  97480. // convert to string
  97481. var array_buffer = new Uint8Array(data);
  97482. var str = '';
  97483. for (var i = 0; i < data.byteLength; i++) {
  97484. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  97485. }
  97486. data = str;
  97487. while (matches = this.solidPattern.exec(data)) {
  97488. var meshName = matches[1];
  97489. var meshNameFromEnd = matches[3];
  97490. if (meshName != meshNameFromEnd) {
  97491. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  97492. return false;
  97493. }
  97494. // check meshesNames
  97495. if (meshesNames && meshName) {
  97496. if (meshesNames instanceof Array) {
  97497. if (!meshesNames.indexOf(meshName)) {
  97498. continue;
  97499. }
  97500. }
  97501. else {
  97502. if (meshName !== meshesNames) {
  97503. continue;
  97504. }
  97505. }
  97506. }
  97507. // stl mesh name can be empty as well
  97508. meshName = meshName || "stlmesh";
  97509. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  97510. this.parseASCII(babylonMesh, matches[2]);
  97511. if (meshes) {
  97512. meshes.push(babylonMesh);
  97513. }
  97514. }
  97515. return true;
  97516. };
  97517. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  97518. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  97519. if (result) {
  97520. scene.createDefaultCameraOrLight();
  97521. }
  97522. return result;
  97523. };
  97524. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  97525. var container = new BABYLON.AssetContainer(scene);
  97526. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  97527. container.removeAllFromScene();
  97528. return container;
  97529. };
  97530. STLFileLoader.prototype.isBinary = function (data) {
  97531. // check if file size is correct for binary stl
  97532. var faceSize, nFaces, reader;
  97533. reader = new DataView(data);
  97534. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  97535. nFaces = reader.getUint32(80, true);
  97536. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  97537. return true;
  97538. }
  97539. // check characters higher than ASCII to confirm binary
  97540. var fileLength = reader.byteLength;
  97541. for (var index = 0; index < fileLength; index++) {
  97542. if (reader.getUint8(index) > 127) {
  97543. return true;
  97544. }
  97545. }
  97546. return false;
  97547. };
  97548. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  97549. var reader = new DataView(data);
  97550. var faces = reader.getUint32(80, true);
  97551. var dataOffset = 84;
  97552. var faceLength = 12 * 4 + 2;
  97553. var offset = 0;
  97554. var positions = new Float32Array(faces * 3 * 3);
  97555. var normals = new Float32Array(faces * 3 * 3);
  97556. var indices = new Uint32Array(faces * 3);
  97557. var indicesCount = 0;
  97558. for (var face = 0; face < faces; face++) {
  97559. var start = dataOffset + face * faceLength;
  97560. var normalX = reader.getFloat32(start, true);
  97561. var normalY = reader.getFloat32(start + 4, true);
  97562. var normalZ = reader.getFloat32(start + 8, true);
  97563. for (var i = 1; i <= 3; i++) {
  97564. var vertexstart = start + i * 12;
  97565. // ordering is intentional to match ascii import
  97566. positions[offset] = reader.getFloat32(vertexstart, true);
  97567. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  97568. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  97569. normals[offset] = normalX;
  97570. normals[offset + 2] = normalY;
  97571. normals[offset + 1] = normalZ;
  97572. offset += 3;
  97573. }
  97574. indices[indicesCount] = indicesCount++;
  97575. indices[indicesCount] = indicesCount++;
  97576. indices[indicesCount] = indicesCount++;
  97577. }
  97578. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  97579. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  97580. mesh.setIndices(indices);
  97581. mesh.computeWorldMatrix(true);
  97582. };
  97583. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  97584. var positions = [];
  97585. var normals = [];
  97586. var indices = [];
  97587. var indicesCount = 0;
  97588. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  97589. var matches;
  97590. while (matches = this.facetsPattern.exec(solidData)) {
  97591. var facet = matches[1];
  97592. //one normal per face
  97593. var normalMatches = this.normalPattern.exec(facet);
  97594. this.normalPattern.lastIndex = 0;
  97595. if (!normalMatches) {
  97596. continue;
  97597. }
  97598. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  97599. var vertexMatch;
  97600. while (vertexMatch = this.vertexPattern.exec(facet)) {
  97601. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  97602. normals.push(normal[0], normal[1], normal[2]);
  97603. }
  97604. indices.push(indicesCount++, indicesCount++, indicesCount++);
  97605. this.vertexPattern.lastIndex = 0;
  97606. }
  97607. this.facetsPattern.lastIndex = 0;
  97608. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  97609. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  97610. mesh.setIndices(indices);
  97611. mesh.computeWorldMatrix(true);
  97612. };
  97613. return STLFileLoader;
  97614. }());
  97615. BABYLON.STLFileLoader = STLFileLoader;
  97616. if (BABYLON.SceneLoader) {
  97617. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  97618. }
  97619. })(BABYLON || (BABYLON = {}));
  97620. //# sourceMappingURL=babylon.stlFileLoader.js.map
  97621. "use strict";
  97622. var BABYLON;
  97623. (function (BABYLON) {
  97624. /**
  97625. * Class reading and parsing the MTL file bundled with the obj file.
  97626. */
  97627. var MTLFileLoader = /** @class */ (function () {
  97628. function MTLFileLoader() {
  97629. // All material loaded from the mtl will be set here
  97630. this.materials = [];
  97631. }
  97632. /**
  97633. * This function will read the mtl file and create each material described inside
  97634. * This function could be improve by adding :
  97635. * -some component missing (Ni, Tf...)
  97636. * -including the specific options available
  97637. *
  97638. * @param scene
  97639. * @param data
  97640. * @param rootUrl
  97641. */
  97642. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  97643. if (data instanceof ArrayBuffer) {
  97644. return;
  97645. }
  97646. //Split the lines from the file
  97647. var lines = data.split('\n');
  97648. //Space char
  97649. var delimiter_pattern = /\s+/;
  97650. //Array with RGB colors
  97651. var color;
  97652. //New material
  97653. var material = null;
  97654. //Look at each line
  97655. for (var i = 0; i < lines.length; i++) {
  97656. var line = lines[i].trim();
  97657. // Blank line or comment
  97658. if (line.length === 0 || line.charAt(0) === '#') {
  97659. continue;
  97660. }
  97661. //Get the first parameter (keyword)
  97662. var pos = line.indexOf(' ');
  97663. var key = (pos >= 0) ? line.substring(0, pos) : line;
  97664. key = key.toLowerCase();
  97665. //Get the data following the key
  97666. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  97667. //This mtl keyword will create the new material
  97668. if (key === "newmtl") {
  97669. //Check if it is the first material.
  97670. // Materials specifications are described after this keyword.
  97671. if (material) {
  97672. //Add the previous material in the material array.
  97673. this.materials.push(material);
  97674. }
  97675. //Create a new material.
  97676. // value is the name of the material read in the mtl file
  97677. material = new BABYLON.StandardMaterial(value, scene);
  97678. }
  97679. else if (key === "kd" && material) {
  97680. // Diffuse color (color under white light) using RGB values
  97681. //value = "r g b"
  97682. color = value.split(delimiter_pattern, 3).map(parseFloat);
  97683. //color = [r,g,b]
  97684. //Set tghe color into the material
  97685. material.diffuseColor = BABYLON.Color3.FromArray(color);
  97686. }
  97687. else if (key === "ka" && material) {
  97688. // Ambient color (color under shadow) using RGB values
  97689. //value = "r g b"
  97690. color = value.split(delimiter_pattern, 3).map(parseFloat);
  97691. //color = [r,g,b]
  97692. //Set tghe color into the material
  97693. material.ambientColor = BABYLON.Color3.FromArray(color);
  97694. }
  97695. else if (key === "ks" && material) {
  97696. // Specular color (color when light is reflected from shiny surface) using RGB values
  97697. //value = "r g b"
  97698. color = value.split(delimiter_pattern, 3).map(parseFloat);
  97699. //color = [r,g,b]
  97700. //Set the color into the material
  97701. material.specularColor = BABYLON.Color3.FromArray(color);
  97702. }
  97703. else if (key === "ke" && material) {
  97704. // Emissive color using RGB values
  97705. color = value.split(delimiter_pattern, 3).map(parseFloat);
  97706. material.emissiveColor = BABYLON.Color3.FromArray(color);
  97707. }
  97708. else if (key === "ns" && material) {
  97709. //value = "Integer"
  97710. material.specularPower = parseFloat(value);
  97711. }
  97712. else if (key === "d" && material) {
  97713. //d is dissolve for current material. It mean alpha for BABYLON
  97714. material.alpha = parseFloat(value);
  97715. //Texture
  97716. //This part can be improved by adding the possible options of texture
  97717. }
  97718. else if (key === "map_ka" && material) {
  97719. // ambient texture map with a loaded image
  97720. //We must first get the folder of the image
  97721. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  97722. }
  97723. else if (key === "map_kd" && material) {
  97724. // Diffuse texture map with a loaded image
  97725. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  97726. }
  97727. else if (key === "map_ks" && material) {
  97728. // Specular texture map with a loaded image
  97729. //We must first get the folder of the image
  97730. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  97731. }
  97732. else if (key === "map_ns") {
  97733. //Specular
  97734. //Specular highlight component
  97735. //We must first get the folder of the image
  97736. //
  97737. //Not supported by BABYLON
  97738. //
  97739. // continue;
  97740. }
  97741. else if (key === "map_bump" && material) {
  97742. //The bump texture
  97743. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  97744. }
  97745. else if (key === "map_d" && material) {
  97746. // The dissolve of the material
  97747. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  97748. //Options for illumination
  97749. }
  97750. else if (key === "illum") {
  97751. //Illumination
  97752. if (value === "0") {
  97753. //That mean Kd == Kd
  97754. }
  97755. else if (value === "1") {
  97756. //Color on and Ambient on
  97757. }
  97758. else if (value === "2") {
  97759. //Highlight on
  97760. }
  97761. else if (value === "3") {
  97762. //Reflection on and Ray trace on
  97763. }
  97764. else if (value === "4") {
  97765. //Transparency: Glass on, Reflection: Ray trace on
  97766. }
  97767. else if (value === "5") {
  97768. //Reflection: Fresnel on and Ray trace on
  97769. }
  97770. else if (value === "6") {
  97771. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  97772. }
  97773. else if (value === "7") {
  97774. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  97775. }
  97776. else if (value === "8") {
  97777. //Reflection on and Ray trace off
  97778. }
  97779. else if (value === "9") {
  97780. //Transparency: Glass on, Reflection: Ray trace off
  97781. }
  97782. else if (value === "10") {
  97783. //Casts shadows onto invisible surfaces
  97784. }
  97785. }
  97786. else {
  97787. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  97788. }
  97789. }
  97790. //At the end of the file, add the last material
  97791. if (material) {
  97792. this.materials.push(material);
  97793. }
  97794. };
  97795. /**
  97796. * Gets the texture for the material.
  97797. *
  97798. * If the material is imported from input file,
  97799. * We sanitize the url to ensure it takes the textre from aside the material.
  97800. *
  97801. * @param rootUrl The root url to load from
  97802. * @param value The value stored in the mtl
  97803. * @return The Texture
  97804. */
  97805. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  97806. if (!value) {
  97807. return null;
  97808. }
  97809. var url = rootUrl;
  97810. // Load from input file.
  97811. if (rootUrl === "file:") {
  97812. var lastDelimiter = value.lastIndexOf("\\");
  97813. if (lastDelimiter === -1) {
  97814. lastDelimiter = value.lastIndexOf("/");
  97815. }
  97816. if (lastDelimiter > -1) {
  97817. url += value.substr(lastDelimiter + 1);
  97818. }
  97819. else {
  97820. url += value;
  97821. }
  97822. }
  97823. else {
  97824. url += value;
  97825. }
  97826. return new BABYLON.Texture(url, scene);
  97827. };
  97828. return MTLFileLoader;
  97829. }());
  97830. BABYLON.MTLFileLoader = MTLFileLoader;
  97831. var OBJFileLoader = /** @class */ (function () {
  97832. function OBJFileLoader() {
  97833. this.name = "obj";
  97834. this.extensions = ".obj";
  97835. this.obj = /^o/;
  97836. this.group = /^g/;
  97837. this.mtllib = /^mtllib /;
  97838. this.usemtl = /^usemtl /;
  97839. this.smooth = /^s /;
  97840. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  97841. // vn float float float
  97842. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  97843. // vt float float
  97844. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  97845. // f vertex vertex vertex ...
  97846. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  97847. // f vertex/uvs vertex/uvs vertex/uvs ...
  97848. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  97849. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  97850. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  97851. // f vertex//normal vertex//normal vertex//normal ...
  97852. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  97853. }
  97854. /**
  97855. * Calls synchronously the MTL file attached to this obj.
  97856. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  97857. * Without this function materials are not displayed in the first frame (but displayed after).
  97858. * In consequence it is impossible to get material information in your HTML file
  97859. *
  97860. * @param url The URL of the MTL file
  97861. * @param rootUrl
  97862. * @param onSuccess Callback function to be called when the MTL file is loaded
  97863. * @private
  97864. */
  97865. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  97866. //The complete path to the mtl file
  97867. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  97868. // Loads through the babylon tools to allow fileInput search.
  97869. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  97870. };
  97871. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  97872. //get the meshes from OBJ file
  97873. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  97874. //Push meshes from OBJ file into the variable mesh of this function
  97875. if (meshes) {
  97876. loadedMeshes.forEach(function (mesh) {
  97877. meshes.push(mesh);
  97878. });
  97879. }
  97880. return true;
  97881. };
  97882. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  97883. //Get the 3D model
  97884. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  97885. };
  97886. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  97887. var container = new BABYLON.AssetContainer(scene);
  97888. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  97889. container.removeAllFromScene();
  97890. return container;
  97891. };
  97892. /**
  97893. * Read the OBJ file and create an Array of meshes.
  97894. * Each mesh contains all information given by the OBJ and the MTL file.
  97895. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  97896. *
  97897. * @param meshesNames
  97898. * @param scene BABYLON.Scene The scene where are displayed the data
  97899. * @param data String The content of the obj file
  97900. * @param rootUrl String The path to the folder
  97901. * @returns Array<AbstractMesh>
  97902. * @private
  97903. */
  97904. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  97905. var positions = []; //values for the positions of vertices
  97906. var normals = []; //Values for the normals
  97907. var uvs = []; //Values for the textures
  97908. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  97909. var handledMesh; //The current mesh of meshes array
  97910. var indicesForBabylon = []; //The list of indices for VertexData
  97911. var wrappedPositionForBabylon = []; //The list of position in vectors
  97912. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  97913. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  97914. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  97915. var curPositionInIndices = 0;
  97916. var hasMeshes = false; //Meshes are defined in the file
  97917. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  97918. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  97919. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  97920. var triangles = []; //Indices from new triangles coming from polygons
  97921. var materialNameFromObj = ""; //The name of the current material
  97922. var fileToLoad = ""; //The name of the mtlFile to load
  97923. var materialsFromMTLFile = new MTLFileLoader();
  97924. var objMeshName = ""; //The name of the current obj mesh
  97925. var increment = 1; //Id for meshes created by the multimaterial
  97926. var isFirstMaterial = true;
  97927. /**
  97928. * Search for obj in the given array.
  97929. * This function is called to check if a couple of data already exists in an array.
  97930. *
  97931. * If found, returns the index of the founded tuple index. Returns -1 if not found
  97932. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  97933. * @param obj Array<number>
  97934. * @returns {boolean}
  97935. */
  97936. var isInArray = function (arr, obj) {
  97937. if (!arr[obj[0]])
  97938. arr[obj[0]] = { normals: [], idx: [] };
  97939. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  97940. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  97941. };
  97942. var isInArrayUV = function (arr, obj) {
  97943. if (!arr[obj[0]])
  97944. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  97945. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  97946. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  97947. return arr[obj[0]].idx[idx];
  97948. }
  97949. return -1;
  97950. };
  97951. /**
  97952. * This function set the data for each triangle.
  97953. * Data are position, normals and uvs
  97954. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  97955. * If the tuple already exist, add only their indice
  97956. *
  97957. * @param indicePositionFromObj Integer The index in positions array
  97958. * @param indiceUvsFromObj Integer The index in uvs array
  97959. * @param indiceNormalFromObj Integer The index in normals array
  97960. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  97961. * @param textureVectorFromOBJ Vector3 The value of uvs
  97962. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  97963. */
  97964. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  97965. //Check if this tuple already exists in the list of tuples
  97966. var _index;
  97967. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  97968. _index = isInArrayUV(tuplePosNorm, [
  97969. indicePositionFromObj,
  97970. indiceNormalFromObj,
  97971. indiceUvsFromObj
  97972. ]);
  97973. }
  97974. else {
  97975. _index = isInArray(tuplePosNorm, [
  97976. indicePositionFromObj,
  97977. indiceNormalFromObj
  97978. ]);
  97979. }
  97980. //If it not exists
  97981. if (_index == -1) {
  97982. //Add an new indice.
  97983. //The array of indices is only an array with his length equal to the number of triangles - 1.
  97984. //We add vertices data in this order
  97985. indicesForBabylon.push(wrappedPositionForBabylon.length);
  97986. //Push the position of vertice for Babylon
  97987. //Each element is a BABYLON.Vector3(x,y,z)
  97988. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  97989. //Push the uvs for Babylon
  97990. //Each element is a BABYLON.Vector3(u,v)
  97991. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  97992. //Push the normals for Babylon
  97993. //Each element is a BABYLON.Vector3(x,y,z)
  97994. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  97995. //Add the tuple in the comparison list
  97996. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  97997. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  97998. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  97999. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  98000. }
  98001. else {
  98002. //The tuple already exists
  98003. //Add the index of the already existing tuple
  98004. //At this index we can get the value of position, normal and uvs of vertex
  98005. indicesForBabylon.push(_index);
  98006. }
  98007. };
  98008. /**
  98009. * Transform BABYLON.Vector() object onto 3 digits in an array
  98010. */
  98011. var unwrapData = function () {
  98012. //Every array has the same length
  98013. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  98014. //Push the x, y, z values of each element in the unwrapped array
  98015. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  98016. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  98017. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  98018. }
  98019. // Reset arrays for the next new meshes
  98020. wrappedPositionForBabylon = [];
  98021. wrappedNormalsForBabylon = [];
  98022. wrappedUvsForBabylon = [];
  98023. tuplePosNorm = [];
  98024. curPositionInIndices = 0;
  98025. };
  98026. /**
  98027. * Create triangles from polygons by recursion
  98028. * The best to understand how it works is to draw it in the same time you get the recursion.
  98029. * It is important to notice that a triangle is a polygon
  98030. * We get 4 patterns of face defined in OBJ File :
  98031. * facePattern1 = ["1","2","3","4","5","6"]
  98032. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  98033. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  98034. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  98035. * Each pattern is divided by the same method
  98036. * @param face Array[String] The indices of elements
  98037. * @param v Integer The variable to increment
  98038. */
  98039. var getTriangles = function (face, v) {
  98040. //Work for each element of the array
  98041. if (v + 1 < face.length) {
  98042. //Add on the triangle variable the indexes to obtain triangles
  98043. triangles.push(face[0], face[v], face[v + 1]);
  98044. //Incrementation for recursion
  98045. v += 1;
  98046. //Recursion
  98047. getTriangles(face, v);
  98048. }
  98049. //Result obtained after 2 iterations:
  98050. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  98051. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  98052. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  98053. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  98054. };
  98055. /**
  98056. * Create triangles and push the data for each polygon for the pattern 1
  98057. * In this pattern we get vertice positions
  98058. * @param face
  98059. * @param v
  98060. */
  98061. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  98062. //Get the indices of triangles for each polygon
  98063. getTriangles(face, v);
  98064. //For each element in the triangles array.
  98065. //This var could contains 1 to an infinity of triangles
  98066. for (var k = 0; k < triangles.length; k++) {
  98067. // Set position indice
  98068. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  98069. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  98070. positions[indicePositionFromObj], //Get the vectors data
  98071. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  98072. );
  98073. }
  98074. //Reset variable for the next line
  98075. triangles = [];
  98076. };
  98077. /**
  98078. * Create triangles and push the data for each polygon for the pattern 2
  98079. * In this pattern we get vertice positions and uvsu
  98080. * @param face
  98081. * @param v
  98082. */
  98083. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  98084. //Get the indices of triangles for each polygon
  98085. getTriangles(face, v);
  98086. for (var k = 0; k < triangles.length; k++) {
  98087. //triangle[k] = "1/1"
  98088. //Split the data for getting position and uv
  98089. var point = triangles[k].split("/"); // ["1", "1"]
  98090. //Set position indice
  98091. var indicePositionFromObj = parseInt(point[0]) - 1;
  98092. //Set uv indice
  98093. var indiceUvsFromObj = parseInt(point[1]) - 1;
  98094. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  98095. positions[indicePositionFromObj], //Get the values for each element
  98096. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  98097. );
  98098. }
  98099. //Reset variable for the next line
  98100. triangles = [];
  98101. };
  98102. /**
  98103. * Create triangles and push the data for each polygon for the pattern 3
  98104. * In this pattern we get vertice positions, uvs and normals
  98105. * @param face
  98106. * @param v
  98107. */
  98108. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  98109. //Get the indices of triangles for each polygon
  98110. getTriangles(face, v);
  98111. for (var k = 0; k < triangles.length; k++) {
  98112. //triangle[k] = "1/1/1"
  98113. //Split the data for getting position, uv, and normals
  98114. var point = triangles[k].split("/"); // ["1", "1", "1"]
  98115. // Set position indice
  98116. var indicePositionFromObj = parseInt(point[0]) - 1;
  98117. // Set uv indice
  98118. var indiceUvsFromObj = parseInt(point[1]) - 1;
  98119. // Set normal indice
  98120. var indiceNormalFromObj = parseInt(point[2]) - 1;
  98121. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  98122. );
  98123. }
  98124. //Reset variable for the next line
  98125. triangles = [];
  98126. };
  98127. /**
  98128. * Create triangles and push the data for each polygon for the pattern 4
  98129. * In this pattern we get vertice positions and normals
  98130. * @param face
  98131. * @param v
  98132. */
  98133. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  98134. getTriangles(face, v);
  98135. for (var k = 0; k < triangles.length; k++) {
  98136. //triangle[k] = "1//1"
  98137. //Split the data for getting position and normals
  98138. var point = triangles[k].split("//"); // ["1", "1"]
  98139. // We check indices, and normals
  98140. var indicePositionFromObj = parseInt(point[0]) - 1;
  98141. var indiceNormalFromObj = parseInt(point[1]) - 1;
  98142. setData(indicePositionFromObj, 1, //Default value for uv
  98143. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  98144. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  98145. }
  98146. //Reset variable for the next line
  98147. triangles = [];
  98148. };
  98149. var addPreviousObjMesh = function () {
  98150. //Check if it is not the first mesh. Otherwise we don't have data.
  98151. if (meshesFromObj.length > 0) {
  98152. //Get the previous mesh for applying the data about the faces
  98153. //=> in obj file, faces definition append after the name of the mesh
  98154. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  98155. //Set the data into Array for the mesh
  98156. unwrapData();
  98157. // Reverse tab. Otherwise face are displayed in the wrong sens
  98158. indicesForBabylon.reverse();
  98159. //Set the information for the mesh
  98160. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  98161. handledMesh.indices = indicesForBabylon.slice();
  98162. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  98163. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  98164. handledMesh.uvs = unwrappedUVForBabylon.slice();
  98165. //Reset the array for the next mesh
  98166. indicesForBabylon = [];
  98167. unwrappedPositionsForBabylon = [];
  98168. unwrappedNormalsForBabylon = [];
  98169. unwrappedUVForBabylon = [];
  98170. }
  98171. };
  98172. //Main function
  98173. //Split the file into lines
  98174. var lines = data.split('\n');
  98175. //Look at each line
  98176. for (var i = 0; i < lines.length; i++) {
  98177. var line = lines[i].trim();
  98178. var result;
  98179. //Comment or newLine
  98180. if (line.length === 0 || line.charAt(0) === '#') {
  98181. continue;
  98182. //Get information about one position possible for the vertices
  98183. }
  98184. else if ((result = this.vertexPattern.exec(line)) !== null) {
  98185. //Create a Vector3 with the position x, y, z
  98186. //Value of result:
  98187. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  98188. //Add the Vector in the list of positions
  98189. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  98190. }
  98191. else if ((result = this.normalPattern.exec(line)) !== null) {
  98192. //Create a Vector3 with the normals x, y, z
  98193. //Value of result
  98194. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  98195. //Add the Vector in the list of normals
  98196. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  98197. }
  98198. else if ((result = this.uvPattern.exec(line)) !== null) {
  98199. //Create a Vector2 with the normals u, v
  98200. //Value of result
  98201. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  98202. //Add the Vector in the list of uvs
  98203. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  98204. //Identify patterns of faces
  98205. //Face could be defined in different type of pattern
  98206. }
  98207. else if ((result = this.facePattern3.exec(line)) !== null) {
  98208. //Value of result:
  98209. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  98210. //Set the data for this face
  98211. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  98212. 1);
  98213. }
  98214. else if ((result = this.facePattern4.exec(line)) !== null) {
  98215. //Value of result:
  98216. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  98217. //Set the data for this face
  98218. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  98219. 1);
  98220. }
  98221. else if ((result = this.facePattern2.exec(line)) !== null) {
  98222. //Value of result:
  98223. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  98224. //Set the data for this face
  98225. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  98226. 1);
  98227. }
  98228. else if ((result = this.facePattern1.exec(line)) !== null) {
  98229. //Value of result
  98230. //["f 1 2 3", "1 2 3"...]
  98231. //Set the data for this face
  98232. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  98233. 1);
  98234. //Define a mesh or an object
  98235. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  98236. }
  98237. else if (this.group.test(line) || this.obj.test(line)) {
  98238. //Create a new mesh corresponding to the name of the group.
  98239. //Definition of the mesh
  98240. var objMesh =
  98241. //Set the name of the current obj mesh
  98242. {
  98243. name: line.substring(2).trim(),
  98244. indices: undefined,
  98245. positions: undefined,
  98246. normals: undefined,
  98247. uvs: undefined,
  98248. materialName: ""
  98249. };
  98250. addPreviousObjMesh();
  98251. //Push the last mesh created with only the name
  98252. meshesFromObj.push(objMesh);
  98253. //Set this variable to indicate that now meshesFromObj has objects defined inside
  98254. hasMeshes = true;
  98255. isFirstMaterial = true;
  98256. increment = 1;
  98257. //Keyword for applying a material
  98258. }
  98259. else if (this.usemtl.test(line)) {
  98260. //Get the name of the material
  98261. materialNameFromObj = line.substring(7).trim();
  98262. //If this new material is in the same mesh
  98263. if (!isFirstMaterial) {
  98264. //Set the data for the previous mesh
  98265. addPreviousObjMesh();
  98266. //Create a new mesh
  98267. var objMesh =
  98268. //Set the name of the current obj mesh
  98269. {
  98270. name: objMeshName + "_mm" + increment.toString(),
  98271. indices: undefined,
  98272. positions: undefined,
  98273. normals: undefined,
  98274. uvs: undefined,
  98275. materialName: materialNameFromObj
  98276. };
  98277. increment++;
  98278. //If meshes are already defined
  98279. meshesFromObj.push(objMesh);
  98280. }
  98281. //Set the material name if the previous line define a mesh
  98282. if (hasMeshes && isFirstMaterial) {
  98283. //Set the material name to the previous mesh (1 material per mesh)
  98284. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  98285. isFirstMaterial = false;
  98286. }
  98287. //Keyword for loading the mtl file
  98288. }
  98289. else if (this.mtllib.test(line)) {
  98290. //Get the name of mtl file
  98291. fileToLoad = line.substring(7).trim();
  98292. //Apply smoothing
  98293. }
  98294. else if (this.smooth.test(line)) {
  98295. // smooth shading => apply smoothing
  98296. //Toda y I don't know it work with babylon and with obj.
  98297. //With the obj file an integer is set
  98298. }
  98299. else {
  98300. //If there is another possibility
  98301. console.log("Unhandled expression at line : " + line);
  98302. }
  98303. }
  98304. //At the end of the file, add the last mesh into the meshesFromObj array
  98305. if (hasMeshes) {
  98306. //Set the data for the last mesh
  98307. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  98308. //Reverse indices for displaying faces in the good sens
  98309. indicesForBabylon.reverse();
  98310. //Get the good array
  98311. unwrapData();
  98312. //Set array
  98313. handledMesh.indices = indicesForBabylon;
  98314. handledMesh.positions = unwrappedPositionsForBabylon;
  98315. handledMesh.normals = unwrappedNormalsForBabylon;
  98316. handledMesh.uvs = unwrappedUVForBabylon;
  98317. }
  98318. //If any o or g keyword found, create a mesj with a random id
  98319. if (!hasMeshes) {
  98320. // reverse tab of indices
  98321. indicesForBabylon.reverse();
  98322. //Get positions normals uvs
  98323. unwrapData();
  98324. //Set data for one mesh
  98325. meshesFromObj.push({
  98326. name: BABYLON.Geometry.RandomId(),
  98327. indices: indicesForBabylon,
  98328. positions: unwrappedPositionsForBabylon,
  98329. normals: unwrappedNormalsForBabylon,
  98330. uvs: unwrappedUVForBabylon,
  98331. materialName: materialNameFromObj
  98332. });
  98333. }
  98334. //Create a BABYLON.Mesh list
  98335. var babylonMeshesArray = []; //The mesh for babylon
  98336. var materialToUse = new Array();
  98337. //Set data for each mesh
  98338. for (var j = 0; j < meshesFromObj.length; j++) {
  98339. //check meshesNames (stlFileLoader)
  98340. if (meshesNames && meshesFromObj[j].name) {
  98341. if (meshesNames instanceof Array) {
  98342. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  98343. continue;
  98344. }
  98345. }
  98346. else {
  98347. if (meshesFromObj[j].name !== meshesNames) {
  98348. continue;
  98349. }
  98350. }
  98351. }
  98352. //Get the current mesh
  98353. //Set the data with VertexBuffer for each mesh
  98354. handledMesh = meshesFromObj[j];
  98355. //Create a BABYLON.Mesh with the name of the obj mesh
  98356. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  98357. //Push the name of the material to an array
  98358. //This is indispensable for the importMesh function
  98359. materialToUse.push(meshesFromObj[j].materialName);
  98360. var vertexData = new BABYLON.VertexData(); //The container for the values
  98361. //Set the data for the babylonMesh
  98362. vertexData.positions = handledMesh.positions;
  98363. vertexData.normals = handledMesh.normals;
  98364. vertexData.uvs = handledMesh.uvs;
  98365. vertexData.indices = handledMesh.indices;
  98366. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  98367. vertexData.applyToMesh(babylonMesh);
  98368. //Push the mesh into an array
  98369. babylonMeshesArray.push(babylonMesh);
  98370. }
  98371. //load the materials
  98372. //Check if we have a file to load
  98373. if (fileToLoad !== "") {
  98374. //Load the file synchronously
  98375. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  98376. //Create materials thanks MTLLoader function
  98377. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  98378. //Look at each material loaded in the mtl file
  98379. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  98380. //Three variables to get all meshes with the same material
  98381. var startIndex = 0;
  98382. var _indices = [];
  98383. var _index;
  98384. //The material from MTL file is used in the meshes loaded
  98385. //Push the indice in an array
  98386. //Check if the material is not used for another mesh
  98387. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  98388. _indices.push(_index);
  98389. startIndex = _index + 1;
  98390. }
  98391. //If the material is not used dispose it
  98392. if (_index == -1 && _indices.length == 0) {
  98393. //If the material is not needed, remove it
  98394. materialsFromMTLFile.materials[n].dispose();
  98395. }
  98396. else {
  98397. for (var o = 0; o < _indices.length; o++) {
  98398. //Apply the material to the BABYLON.Mesh for each mesh with the material
  98399. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  98400. }
  98401. }
  98402. }
  98403. });
  98404. }
  98405. //Return an array with all BABYLON.Mesh
  98406. return babylonMeshesArray;
  98407. };
  98408. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  98409. return OBJFileLoader;
  98410. }());
  98411. BABYLON.OBJFileLoader = OBJFileLoader;
  98412. if (BABYLON.SceneLoader) {
  98413. //Add this loader into the register plugin
  98414. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  98415. }
  98416. })(BABYLON || (BABYLON = {}));
  98417. //# sourceMappingURL=babylon.objFileLoader.js.map
  98418. "use strict";
  98419. var BABYLON;
  98420. (function (BABYLON) {
  98421. var GLTFLoaderCoordinateSystemMode;
  98422. (function (GLTFLoaderCoordinateSystemMode) {
  98423. /**
  98424. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  98425. */
  98426. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  98427. /**
  98428. * Sets the useRightHandedSystem flag on the scene.
  98429. */
  98430. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  98431. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  98432. var GLTFLoaderAnimationStartMode;
  98433. (function (GLTFLoaderAnimationStartMode) {
  98434. /**
  98435. * No animation will start.
  98436. */
  98437. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  98438. /**
  98439. * The first animation will start.
  98440. */
  98441. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  98442. /**
  98443. * All animations will start.
  98444. */
  98445. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  98446. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  98447. var GLTFLoaderState;
  98448. (function (GLTFLoaderState) {
  98449. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  98450. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  98451. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  98452. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  98453. var GLTFFileLoader = /** @class */ (function () {
  98454. function GLTFFileLoader() {
  98455. // #region Common options
  98456. /**
  98457. * Raised when the asset has been parsed.
  98458. * The data.json property stores the glTF JSON.
  98459. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  98460. */
  98461. this.onParsedObservable = new BABYLON.Observable();
  98462. // #endregion
  98463. // #region V2 options
  98464. /**
  98465. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  98466. */
  98467. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  98468. /**
  98469. * The animation start mode (NONE, FIRST, ALL).
  98470. */
  98471. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  98472. /**
  98473. * Set to true to compile materials before raising the success callback.
  98474. */
  98475. this.compileMaterials = false;
  98476. /**
  98477. * Set to true to also compile materials with clip planes.
  98478. */
  98479. this.useClipPlane = false;
  98480. /**
  98481. * Set to true to compile shadow generators before raising the success callback.
  98482. */
  98483. this.compileShadowGenerators = false;
  98484. /**
  98485. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  98486. */
  98487. this.onMeshLoadedObservable = new BABYLON.Observable();
  98488. /**
  98489. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  98490. */
  98491. this.onTextureLoadedObservable = new BABYLON.Observable();
  98492. /**
  98493. * Raised when the loader creates a material after parsing the glTF properties of the material.
  98494. */
  98495. this.onMaterialLoadedObservable = new BABYLON.Observable();
  98496. /**
  98497. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  98498. * For assets with LODs, raised when all of the LODs are complete.
  98499. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  98500. */
  98501. this.onCompleteObservable = new BABYLON.Observable();
  98502. /**
  98503. * Raised when the loader is disposed.
  98504. */
  98505. this.onDisposeObservable = new BABYLON.Observable();
  98506. /**
  98507. * Raised after a loader extension is created.
  98508. * Set additional options for a loader extension in this event.
  98509. */
  98510. this.onExtensionLoadedObservable = new BABYLON.Observable();
  98511. // #endregion
  98512. this._loader = null;
  98513. this.name = "gltf";
  98514. this.extensions = {
  98515. ".gltf": { isBinary: false },
  98516. ".glb": { isBinary: true }
  98517. };
  98518. }
  98519. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  98520. set: function (callback) {
  98521. if (this._onParsedObserver) {
  98522. this.onParsedObservable.remove(this._onParsedObserver);
  98523. }
  98524. this._onParsedObserver = this.onParsedObservable.add(callback);
  98525. },
  98526. enumerable: true,
  98527. configurable: true
  98528. });
  98529. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  98530. set: function (callback) {
  98531. if (this._onMeshLoadedObserver) {
  98532. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  98533. }
  98534. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  98535. },
  98536. enumerable: true,
  98537. configurable: true
  98538. });
  98539. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  98540. set: function (callback) {
  98541. if (this._onTextureLoadedObserver) {
  98542. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  98543. }
  98544. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  98545. },
  98546. enumerable: true,
  98547. configurable: true
  98548. });
  98549. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  98550. set: function (callback) {
  98551. if (this._onMaterialLoadedObserver) {
  98552. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  98553. }
  98554. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  98555. },
  98556. enumerable: true,
  98557. configurable: true
  98558. });
  98559. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  98560. set: function (callback) {
  98561. if (this._onCompleteObserver) {
  98562. this.onCompleteObservable.remove(this._onCompleteObserver);
  98563. }
  98564. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  98565. },
  98566. enumerable: true,
  98567. configurable: true
  98568. });
  98569. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  98570. set: function (callback) {
  98571. if (this._onDisposeObserver) {
  98572. this.onDisposeObservable.remove(this._onDisposeObserver);
  98573. }
  98574. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98575. },
  98576. enumerable: true,
  98577. configurable: true
  98578. });
  98579. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  98580. set: function (callback) {
  98581. if (this._onExtensionLoadedObserver) {
  98582. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  98583. }
  98584. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  98585. },
  98586. enumerable: true,
  98587. configurable: true
  98588. });
  98589. /**
  98590. * Gets a promise that resolves when the asset is completely loaded.
  98591. * @returns A promise that resolves when the asset is completely loaded.
  98592. */
  98593. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  98594. var _this = this;
  98595. return new Promise(function (resolve) {
  98596. _this.onCompleteObservable.add(function () {
  98597. resolve();
  98598. }, undefined, undefined, undefined, true);
  98599. });
  98600. };
  98601. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  98602. /**
  98603. * The loader state or null if not active.
  98604. */
  98605. get: function () {
  98606. return this._loader ? this._loader.state : null;
  98607. },
  98608. enumerable: true,
  98609. configurable: true
  98610. });
  98611. /**
  98612. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  98613. */
  98614. GLTFFileLoader.prototype.dispose = function () {
  98615. if (this._loader) {
  98616. this._loader.dispose();
  98617. this._loader = null;
  98618. }
  98619. this.onMeshLoadedObservable.clear();
  98620. this.onTextureLoadedObservable.clear();
  98621. this.onMaterialLoadedObservable.clear();
  98622. this.onDisposeObservable.notifyObservers(this);
  98623. this.onDisposeObservable.clear();
  98624. };
  98625. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  98626. var _this = this;
  98627. return Promise.resolve().then(function () {
  98628. var loaderData = _this._parse(data);
  98629. _this._loader = _this._getLoader(loaderData);
  98630. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  98631. });
  98632. };
  98633. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  98634. var _this = this;
  98635. return Promise.resolve().then(function () {
  98636. var loaderData = _this._parse(data);
  98637. _this._loader = _this._getLoader(loaderData);
  98638. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  98639. });
  98640. };
  98641. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  98642. var _this = this;
  98643. return Promise.resolve().then(function () {
  98644. var loaderData = _this._parse(data);
  98645. _this._loader = _this._getLoader(loaderData);
  98646. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  98647. var container = new BABYLON.AssetContainer(scene);
  98648. Array.prototype.push.apply(container.meshes, result.meshes);
  98649. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  98650. Array.prototype.push.apply(container.skeletons, result.skeletons);
  98651. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  98652. container.removeAllFromScene();
  98653. return container;
  98654. });
  98655. });
  98656. };
  98657. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  98658. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  98659. };
  98660. GLTFFileLoader.prototype.createPlugin = function () {
  98661. return new GLTFFileLoader();
  98662. };
  98663. GLTFFileLoader.prototype._parse = function (data) {
  98664. var parsedData;
  98665. if (data instanceof ArrayBuffer) {
  98666. parsedData = GLTFFileLoader._parseBinary(data);
  98667. }
  98668. else {
  98669. parsedData = {
  98670. json: JSON.parse(data),
  98671. bin: null
  98672. };
  98673. }
  98674. this.onParsedObservable.notifyObservers(parsedData);
  98675. this.onParsedObservable.clear();
  98676. return parsedData;
  98677. };
  98678. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  98679. var _this = this;
  98680. var loaderVersion = { major: 2, minor: 0 };
  98681. var asset = loaderData.json.asset || {};
  98682. var version = GLTFFileLoader._parseVersion(asset.version);
  98683. if (!version) {
  98684. throw new Error("Invalid version: " + asset.version);
  98685. }
  98686. if (asset.minVersion !== undefined) {
  98687. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  98688. if (!minVersion) {
  98689. throw new Error("Invalid minimum version: " + asset.minVersion);
  98690. }
  98691. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  98692. throw new Error("Incompatible minimum version: " + asset.minVersion);
  98693. }
  98694. }
  98695. var createLoaders = {
  98696. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  98697. 2: GLTFFileLoader.CreateGLTFLoaderV2
  98698. };
  98699. var createLoader = createLoaders[version.major];
  98700. if (!createLoader) {
  98701. throw new Error("Unsupported version: " + asset.version);
  98702. }
  98703. var loader = createLoader();
  98704. loader.coordinateSystemMode = this.coordinateSystemMode;
  98705. loader.animationStartMode = this.animationStartMode;
  98706. loader.compileMaterials = this.compileMaterials;
  98707. loader.useClipPlane = this.useClipPlane;
  98708. loader.compileShadowGenerators = this.compileShadowGenerators;
  98709. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  98710. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  98711. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  98712. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  98713. loader.onCompleteObservable.add(function () {
  98714. _this.onMeshLoadedObservable.clear();
  98715. _this.onTextureLoadedObservable.clear();
  98716. _this.onMaterialLoadedObservable.clear();
  98717. _this.onCompleteObservable.notifyObservers(_this);
  98718. _this.onCompleteObservable.clear();
  98719. });
  98720. return loader;
  98721. };
  98722. GLTFFileLoader._parseBinary = function (data) {
  98723. var Binary = {
  98724. Magic: 0x46546C67
  98725. };
  98726. var binaryReader = new BinaryReader(data);
  98727. var magic = binaryReader.readUint32();
  98728. if (magic !== Binary.Magic) {
  98729. throw new Error("Unexpected magic: " + magic);
  98730. }
  98731. var version = binaryReader.readUint32();
  98732. switch (version) {
  98733. case 1: return GLTFFileLoader._parseV1(binaryReader);
  98734. case 2: return GLTFFileLoader._parseV2(binaryReader);
  98735. }
  98736. throw new Error("Unsupported version: " + version);
  98737. };
  98738. GLTFFileLoader._parseV1 = function (binaryReader) {
  98739. var ContentFormat = {
  98740. JSON: 0
  98741. };
  98742. var length = binaryReader.readUint32();
  98743. if (length != binaryReader.getLength()) {
  98744. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  98745. }
  98746. var contentLength = binaryReader.readUint32();
  98747. var contentFormat = binaryReader.readUint32();
  98748. var content;
  98749. switch (contentFormat) {
  98750. case ContentFormat.JSON: {
  98751. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  98752. break;
  98753. }
  98754. default: {
  98755. throw new Error("Unexpected content format: " + contentFormat);
  98756. }
  98757. }
  98758. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  98759. var body = binaryReader.readUint8Array(bytesRemaining);
  98760. return {
  98761. json: content,
  98762. bin: body
  98763. };
  98764. };
  98765. GLTFFileLoader._parseV2 = function (binaryReader) {
  98766. var ChunkFormat = {
  98767. JSON: 0x4E4F534A,
  98768. BIN: 0x004E4942
  98769. };
  98770. var length = binaryReader.readUint32();
  98771. if (length !== binaryReader.getLength()) {
  98772. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  98773. }
  98774. // JSON chunk
  98775. var chunkLength = binaryReader.readUint32();
  98776. var chunkFormat = binaryReader.readUint32();
  98777. if (chunkFormat !== ChunkFormat.JSON) {
  98778. throw new Error("First chunk format is not JSON");
  98779. }
  98780. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  98781. // Look for BIN chunk
  98782. var bin = null;
  98783. while (binaryReader.getPosition() < binaryReader.getLength()) {
  98784. var chunkLength_1 = binaryReader.readUint32();
  98785. var chunkFormat_1 = binaryReader.readUint32();
  98786. switch (chunkFormat_1) {
  98787. case ChunkFormat.JSON: {
  98788. throw new Error("Unexpected JSON chunk");
  98789. }
  98790. case ChunkFormat.BIN: {
  98791. bin = binaryReader.readUint8Array(chunkLength_1);
  98792. break;
  98793. }
  98794. default: {
  98795. // ignore unrecognized chunkFormat
  98796. binaryReader.skipBytes(chunkLength_1);
  98797. break;
  98798. }
  98799. }
  98800. }
  98801. return {
  98802. json: json,
  98803. bin: bin
  98804. };
  98805. };
  98806. GLTFFileLoader._parseVersion = function (version) {
  98807. if (version === "1.0" || version === "1.0.1") {
  98808. return {
  98809. major: 1,
  98810. minor: 0
  98811. };
  98812. }
  98813. var match = (version + "").match(/^(\d+)\.(\d+)/);
  98814. if (!match) {
  98815. return null;
  98816. }
  98817. return {
  98818. major: parseInt(match[1]),
  98819. minor: parseInt(match[2])
  98820. };
  98821. };
  98822. GLTFFileLoader._compareVersion = function (a, b) {
  98823. if (a.major > b.major)
  98824. return 1;
  98825. if (a.major < b.major)
  98826. return -1;
  98827. if (a.minor > b.minor)
  98828. return 1;
  98829. if (a.minor < b.minor)
  98830. return -1;
  98831. return 0;
  98832. };
  98833. GLTFFileLoader._decodeBufferToText = function (buffer) {
  98834. var result = "";
  98835. var length = buffer.byteLength;
  98836. for (var i = 0; i < length; i++) {
  98837. result += String.fromCharCode(buffer[i]);
  98838. }
  98839. return result;
  98840. };
  98841. // #endregion
  98842. // #region V1 options
  98843. GLTFFileLoader.IncrementalLoading = true;
  98844. GLTFFileLoader.HomogeneousCoordinates = false;
  98845. return GLTFFileLoader;
  98846. }());
  98847. BABYLON.GLTFFileLoader = GLTFFileLoader;
  98848. var BinaryReader = /** @class */ (function () {
  98849. function BinaryReader(arrayBuffer) {
  98850. this._arrayBuffer = arrayBuffer;
  98851. this._dataView = new DataView(arrayBuffer);
  98852. this._byteOffset = 0;
  98853. }
  98854. BinaryReader.prototype.getPosition = function () {
  98855. return this._byteOffset;
  98856. };
  98857. BinaryReader.prototype.getLength = function () {
  98858. return this._arrayBuffer.byteLength;
  98859. };
  98860. BinaryReader.prototype.readUint32 = function () {
  98861. var value = this._dataView.getUint32(this._byteOffset, true);
  98862. this._byteOffset += 4;
  98863. return value;
  98864. };
  98865. BinaryReader.prototype.readUint8Array = function (length) {
  98866. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  98867. this._byteOffset += length;
  98868. return value;
  98869. };
  98870. BinaryReader.prototype.skipBytes = function (length) {
  98871. this._byteOffset += length;
  98872. };
  98873. return BinaryReader;
  98874. }());
  98875. if (BABYLON.SceneLoader) {
  98876. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  98877. }
  98878. })(BABYLON || (BABYLON = {}));
  98879. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  98880. "use strict";
  98881. var BABYLON;
  98882. (function (BABYLON) {
  98883. var GLTF1;
  98884. (function (GLTF1) {
  98885. /**
  98886. * Enums
  98887. */
  98888. var EComponentType;
  98889. (function (EComponentType) {
  98890. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  98891. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  98892. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  98893. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  98894. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  98895. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  98896. var EShaderType;
  98897. (function (EShaderType) {
  98898. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  98899. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  98900. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  98901. var EParameterType;
  98902. (function (EParameterType) {
  98903. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  98904. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  98905. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  98906. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  98907. EParameterType[EParameterType["INT"] = 5124] = "INT";
  98908. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  98909. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  98910. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  98911. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  98912. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  98913. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  98914. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  98915. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  98916. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  98917. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  98918. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  98919. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  98920. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  98921. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  98922. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  98923. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  98924. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  98925. var ETextureWrapMode;
  98926. (function (ETextureWrapMode) {
  98927. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  98928. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  98929. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  98930. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  98931. var ETextureFilterType;
  98932. (function (ETextureFilterType) {
  98933. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  98934. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  98935. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  98936. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  98937. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  98938. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  98939. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  98940. var ETextureFormat;
  98941. (function (ETextureFormat) {
  98942. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  98943. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  98944. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  98945. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  98946. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  98947. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  98948. var ECullingType;
  98949. (function (ECullingType) {
  98950. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  98951. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  98952. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  98953. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  98954. var EBlendingFunction;
  98955. (function (EBlendingFunction) {
  98956. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  98957. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  98958. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  98959. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  98960. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  98961. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  98962. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  98963. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  98964. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  98965. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  98966. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  98967. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  98968. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  98969. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  98970. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  98971. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  98972. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  98973. })(BABYLON || (BABYLON = {}));
  98974. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  98975. "use strict";
  98976. var BABYLON;
  98977. (function (BABYLON) {
  98978. var GLTF1;
  98979. (function (GLTF1) {
  98980. /**
  98981. * Tokenizer. Used for shaders compatibility
  98982. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  98983. */
  98984. var ETokenType;
  98985. (function (ETokenType) {
  98986. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  98987. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  98988. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  98989. })(ETokenType || (ETokenType = {}));
  98990. var Tokenizer = /** @class */ (function () {
  98991. function Tokenizer(toParse) {
  98992. this._pos = 0;
  98993. this.currentToken = ETokenType.UNKNOWN;
  98994. this.currentIdentifier = "";
  98995. this.currentString = "";
  98996. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  98997. this._toParse = toParse;
  98998. this._maxPos = toParse.length;
  98999. }
  99000. Tokenizer.prototype.getNextToken = function () {
  99001. if (this.isEnd())
  99002. return ETokenType.END_OF_INPUT;
  99003. this.currentString = this.read();
  99004. this.currentToken = ETokenType.UNKNOWN;
  99005. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  99006. this.currentToken = ETokenType.IDENTIFIER;
  99007. this.currentIdentifier = this.currentString;
  99008. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  99009. this.currentIdentifier += this.currentString;
  99010. this.forward();
  99011. }
  99012. }
  99013. return this.currentToken;
  99014. };
  99015. Tokenizer.prototype.peek = function () {
  99016. return this._toParse[this._pos];
  99017. };
  99018. Tokenizer.prototype.read = function () {
  99019. return this._toParse[this._pos++];
  99020. };
  99021. Tokenizer.prototype.forward = function () {
  99022. this._pos++;
  99023. };
  99024. Tokenizer.prototype.isEnd = function () {
  99025. return this._pos >= this._maxPos;
  99026. };
  99027. return Tokenizer;
  99028. }());
  99029. /**
  99030. * Values
  99031. */
  99032. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  99033. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  99034. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  99035. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  99036. /**
  99037. * Parse
  99038. */
  99039. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  99040. for (var buf in parsedBuffers) {
  99041. var parsedBuffer = parsedBuffers[buf];
  99042. gltfRuntime.buffers[buf] = parsedBuffer;
  99043. gltfRuntime.buffersCount++;
  99044. }
  99045. };
  99046. var parseShaders = function (parsedShaders, gltfRuntime) {
  99047. for (var sha in parsedShaders) {
  99048. var parsedShader = parsedShaders[sha];
  99049. gltfRuntime.shaders[sha] = parsedShader;
  99050. gltfRuntime.shaderscount++;
  99051. }
  99052. };
  99053. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  99054. for (var object in parsedObjects) {
  99055. var parsedObject = parsedObjects[object];
  99056. gltfRuntime[runtimeProperty][object] = parsedObject;
  99057. }
  99058. };
  99059. /**
  99060. * Utils
  99061. */
  99062. var normalizeUVs = function (buffer) {
  99063. if (!buffer) {
  99064. return;
  99065. }
  99066. for (var i = 0; i < buffer.length / 2; i++) {
  99067. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  99068. }
  99069. };
  99070. var getAttribute = function (attributeParameter) {
  99071. if (attributeParameter.semantic === "NORMAL") {
  99072. return "normal";
  99073. }
  99074. else if (attributeParameter.semantic === "POSITION") {
  99075. return "position";
  99076. }
  99077. else if (attributeParameter.semantic === "JOINT") {
  99078. return "matricesIndices";
  99079. }
  99080. else if (attributeParameter.semantic === "WEIGHT") {
  99081. return "matricesWeights";
  99082. }
  99083. else if (attributeParameter.semantic === "COLOR") {
  99084. return "color";
  99085. }
  99086. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  99087. var channel = Number(attributeParameter.semantic.split("_")[1]);
  99088. return "uv" + (channel === 0 ? "" : channel + 1);
  99089. }
  99090. return null;
  99091. };
  99092. /**
  99093. * Loads and creates animations
  99094. */
  99095. var loadAnimations = function (gltfRuntime) {
  99096. for (var anim in gltfRuntime.animations) {
  99097. var animation = gltfRuntime.animations[anim];
  99098. if (!animation.channels || !animation.samplers) {
  99099. continue;
  99100. }
  99101. var lastAnimation = null;
  99102. for (var i = 0; i < animation.channels.length; i++) {
  99103. // Get parameters and load buffers
  99104. var channel = animation.channels[i];
  99105. var sampler = animation.samplers[channel.sampler];
  99106. if (!sampler) {
  99107. continue;
  99108. }
  99109. var inputData = null;
  99110. var outputData = null;
  99111. if (animation.parameters) {
  99112. inputData = animation.parameters[sampler.input];
  99113. outputData = animation.parameters[sampler.output];
  99114. }
  99115. else {
  99116. inputData = sampler.input;
  99117. outputData = sampler.output;
  99118. }
  99119. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  99120. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  99121. var targetID = channel.target.id;
  99122. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  99123. if (targetNode === null) {
  99124. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  99125. }
  99126. if (targetNode === null) {
  99127. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  99128. continue;
  99129. }
  99130. var isBone = targetNode instanceof BABYLON.Bone;
  99131. // Get target path (position, rotation or scaling)
  99132. var targetPath = channel.target.path;
  99133. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  99134. if (targetPathIndex !== -1) {
  99135. targetPath = babylonAnimationPaths[targetPathIndex];
  99136. }
  99137. // Determine animation type
  99138. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  99139. if (!isBone) {
  99140. if (targetPath === "rotationQuaternion") {
  99141. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  99142. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  99143. }
  99144. else {
  99145. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  99146. }
  99147. }
  99148. // Create animation and key frames
  99149. var babylonAnimation = null;
  99150. var keys = [];
  99151. var arrayOffset = 0;
  99152. var modifyKey = false;
  99153. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  99154. babylonAnimation = lastAnimation;
  99155. modifyKey = true;
  99156. }
  99157. if (!modifyKey) {
  99158. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  99159. }
  99160. // For each frame
  99161. for (var j = 0; j < bufferInput.length; j++) {
  99162. var value = null;
  99163. if (targetPath === "rotationQuaternion") {
  99164. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  99165. arrayOffset += 4;
  99166. }
  99167. else {
  99168. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  99169. arrayOffset += 3;
  99170. }
  99171. if (isBone) {
  99172. var bone = targetNode;
  99173. var translation = BABYLON.Vector3.Zero();
  99174. var rotationQuaternion = new BABYLON.Quaternion();
  99175. var scaling = BABYLON.Vector3.Zero();
  99176. // Warning on decompose
  99177. var mat = bone.getBaseMatrix();
  99178. if (modifyKey && lastAnimation) {
  99179. mat = lastAnimation.getKeys()[j].value;
  99180. }
  99181. mat.decompose(scaling, rotationQuaternion, translation);
  99182. if (targetPath === "position") {
  99183. translation = value;
  99184. }
  99185. else if (targetPath === "rotationQuaternion") {
  99186. rotationQuaternion = value;
  99187. }
  99188. else {
  99189. scaling = value;
  99190. }
  99191. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  99192. }
  99193. if (!modifyKey) {
  99194. keys.push({
  99195. frame: bufferInput[j],
  99196. value: value
  99197. });
  99198. }
  99199. else if (lastAnimation) {
  99200. lastAnimation.getKeys()[j].value = value;
  99201. }
  99202. }
  99203. // Finish
  99204. if (!modifyKey && babylonAnimation) {
  99205. babylonAnimation.setKeys(keys);
  99206. targetNode.animations.push(babylonAnimation);
  99207. }
  99208. lastAnimation = babylonAnimation;
  99209. gltfRuntime.scene.stopAnimation(targetNode);
  99210. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  99211. }
  99212. }
  99213. };
  99214. /**
  99215. * Returns the bones transformation matrix
  99216. */
  99217. var configureBoneTransformation = function (node) {
  99218. var mat = null;
  99219. if (node.translation || node.rotation || node.scale) {
  99220. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  99221. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  99222. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  99223. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  99224. }
  99225. else {
  99226. mat = BABYLON.Matrix.FromArray(node.matrix);
  99227. }
  99228. return mat;
  99229. };
  99230. /**
  99231. * Returns the parent bone
  99232. */
  99233. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  99234. // Try to find
  99235. for (var i = 0; i < newSkeleton.bones.length; i++) {
  99236. if (newSkeleton.bones[i].name === jointName) {
  99237. return newSkeleton.bones[i];
  99238. }
  99239. }
  99240. // Not found, search in gltf nodes
  99241. var nodes = gltfRuntime.nodes;
  99242. for (var nde in nodes) {
  99243. var node = nodes[nde];
  99244. if (!node.jointName) {
  99245. continue;
  99246. }
  99247. var children = node.children;
  99248. for (var i = 0; i < children.length; i++) {
  99249. var child = gltfRuntime.nodes[children[i]];
  99250. if (!child.jointName) {
  99251. continue;
  99252. }
  99253. if (child.jointName === jointName) {
  99254. var mat = configureBoneTransformation(node);
  99255. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  99256. bone.id = nde;
  99257. return bone;
  99258. }
  99259. }
  99260. }
  99261. return null;
  99262. };
  99263. /**
  99264. * Returns the appropriate root node
  99265. */
  99266. var getNodeToRoot = function (nodesToRoot, id) {
  99267. for (var i = 0; i < nodesToRoot.length; i++) {
  99268. var nodeToRoot = nodesToRoot[i];
  99269. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  99270. var child = nodeToRoot.node.children[j];
  99271. if (child === id) {
  99272. return nodeToRoot.bone;
  99273. }
  99274. }
  99275. }
  99276. return null;
  99277. };
  99278. /**
  99279. * Returns the node with the joint name
  99280. */
  99281. var getJointNode = function (gltfRuntime, jointName) {
  99282. var nodes = gltfRuntime.nodes;
  99283. var node = nodes[jointName];
  99284. if (node) {
  99285. return {
  99286. node: node,
  99287. id: jointName
  99288. };
  99289. }
  99290. for (var nde in nodes) {
  99291. node = nodes[nde];
  99292. if (node.jointName === jointName) {
  99293. return {
  99294. node: node,
  99295. id: nde
  99296. };
  99297. }
  99298. }
  99299. return null;
  99300. };
  99301. /**
  99302. * Checks if a nodes is in joints
  99303. */
  99304. var nodeIsInJoints = function (skins, id) {
  99305. for (var i = 0; i < skins.jointNames.length; i++) {
  99306. if (skins.jointNames[i] === id) {
  99307. return true;
  99308. }
  99309. }
  99310. return false;
  99311. };
  99312. /**
  99313. * Fills the nodes to root for bones and builds hierarchy
  99314. */
  99315. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  99316. // Creates nodes for root
  99317. for (var nde in gltfRuntime.nodes) {
  99318. var node = gltfRuntime.nodes[nde];
  99319. var id = nde;
  99320. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  99321. continue;
  99322. }
  99323. // Create node to root bone
  99324. var mat = configureBoneTransformation(node);
  99325. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  99326. bone.id = id;
  99327. nodesToRoot.push({ bone: bone, node: node, id: id });
  99328. }
  99329. // Parenting
  99330. for (var i = 0; i < nodesToRoot.length; i++) {
  99331. var nodeToRoot = nodesToRoot[i];
  99332. var children = nodeToRoot.node.children;
  99333. for (var j = 0; j < children.length; j++) {
  99334. var child = null;
  99335. for (var k = 0; k < nodesToRoot.length; k++) {
  99336. if (nodesToRoot[k].id === children[j]) {
  99337. child = nodesToRoot[k];
  99338. break;
  99339. }
  99340. }
  99341. if (child) {
  99342. child.bone._parent = nodeToRoot.bone;
  99343. nodeToRoot.bone.children.push(child.bone);
  99344. }
  99345. }
  99346. }
  99347. };
  99348. /**
  99349. * Imports a skeleton
  99350. */
  99351. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  99352. if (!newSkeleton) {
  99353. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  99354. }
  99355. if (!skins.babylonSkeleton) {
  99356. return newSkeleton;
  99357. }
  99358. // Find the root bones
  99359. var nodesToRoot = [];
  99360. var nodesToRootToAdd = [];
  99361. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  99362. newSkeleton.bones = [];
  99363. // Joints
  99364. for (var i = 0; i < skins.jointNames.length; i++) {
  99365. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  99366. if (!jointNode) {
  99367. continue;
  99368. }
  99369. var node = jointNode.node;
  99370. if (!node) {
  99371. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  99372. continue;
  99373. }
  99374. var id = jointNode.id;
  99375. // Optimize, if the bone already exists...
  99376. var existingBone = gltfRuntime.scene.getBoneByID(id);
  99377. if (existingBone) {
  99378. newSkeleton.bones.push(existingBone);
  99379. continue;
  99380. }
  99381. // Search for parent bone
  99382. var foundBone = false;
  99383. var parentBone = null;
  99384. for (var j = 0; j < i; j++) {
  99385. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  99386. if (!jointNode_1) {
  99387. continue;
  99388. }
  99389. var joint = jointNode_1.node;
  99390. if (!joint) {
  99391. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  99392. continue;
  99393. }
  99394. var children = joint.children;
  99395. if (!children) {
  99396. continue;
  99397. }
  99398. foundBone = false;
  99399. for (var k = 0; k < children.length; k++) {
  99400. if (children[k] === id) {
  99401. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  99402. foundBone = true;
  99403. break;
  99404. }
  99405. }
  99406. if (foundBone) {
  99407. break;
  99408. }
  99409. }
  99410. // Create bone
  99411. var mat = configureBoneTransformation(node);
  99412. if (!parentBone && nodesToRoot.length > 0) {
  99413. parentBone = getNodeToRoot(nodesToRoot, id);
  99414. if (parentBone) {
  99415. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  99416. nodesToRootToAdd.push(parentBone);
  99417. }
  99418. }
  99419. }
  99420. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  99421. bone.id = id;
  99422. }
  99423. // Polish
  99424. var bones = newSkeleton.bones;
  99425. newSkeleton.bones = [];
  99426. for (var i = 0; i < skins.jointNames.length; i++) {
  99427. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  99428. if (!jointNode) {
  99429. continue;
  99430. }
  99431. for (var j = 0; j < bones.length; j++) {
  99432. if (bones[j].id === jointNode.id) {
  99433. newSkeleton.bones.push(bones[j]);
  99434. break;
  99435. }
  99436. }
  99437. }
  99438. newSkeleton.prepare();
  99439. // Finish
  99440. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  99441. newSkeleton.bones.push(nodesToRootToAdd[i]);
  99442. }
  99443. return newSkeleton;
  99444. };
  99445. /**
  99446. * Imports a mesh and its geometries
  99447. */
  99448. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  99449. if (!newMesh) {
  99450. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  99451. newMesh.id = id;
  99452. }
  99453. if (!node.babylonNode) {
  99454. return newMesh;
  99455. }
  99456. var subMaterials = [];
  99457. var vertexData = null;
  99458. var verticesStarts = new Array();
  99459. var verticesCounts = new Array();
  99460. var indexStarts = new Array();
  99461. var indexCounts = new Array();
  99462. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  99463. var meshID = meshes[meshIndex];
  99464. var mesh = gltfRuntime.meshes[meshID];
  99465. if (!mesh) {
  99466. continue;
  99467. }
  99468. // Positions, normals and UVs
  99469. for (var i = 0; i < mesh.primitives.length; i++) {
  99470. // Temporary vertex data
  99471. var tempVertexData = new BABYLON.VertexData();
  99472. var primitive = mesh.primitives[i];
  99473. if (primitive.mode !== 4) {
  99474. // continue;
  99475. }
  99476. var attributes = primitive.attributes;
  99477. var accessor = null;
  99478. var buffer = null;
  99479. // Set positions, normal and uvs
  99480. for (var semantic in attributes) {
  99481. // Link accessor and buffer view
  99482. accessor = gltfRuntime.accessors[attributes[semantic]];
  99483. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  99484. if (semantic === "NORMAL") {
  99485. tempVertexData.normals = new Float32Array(buffer.length);
  99486. tempVertexData.normals.set(buffer);
  99487. }
  99488. else if (semantic === "POSITION") {
  99489. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  99490. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  99491. for (var j = 0; j < buffer.length; j += 4) {
  99492. tempVertexData.positions[j] = buffer[j];
  99493. tempVertexData.positions[j + 1] = buffer[j + 1];
  99494. tempVertexData.positions[j + 2] = buffer[j + 2];
  99495. }
  99496. }
  99497. else {
  99498. tempVertexData.positions = new Float32Array(buffer.length);
  99499. tempVertexData.positions.set(buffer);
  99500. }
  99501. verticesCounts.push(tempVertexData.positions.length);
  99502. }
  99503. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  99504. var channel = Number(semantic.split("_")[1]);
  99505. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  99506. var uvs = new Float32Array(buffer.length);
  99507. uvs.set(buffer);
  99508. normalizeUVs(uvs);
  99509. tempVertexData.set(uvs, uvKind);
  99510. }
  99511. else if (semantic === "JOINT") {
  99512. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  99513. tempVertexData.matricesIndices.set(buffer);
  99514. }
  99515. else if (semantic === "WEIGHT") {
  99516. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  99517. tempVertexData.matricesWeights.set(buffer);
  99518. }
  99519. else if (semantic === "COLOR") {
  99520. tempVertexData.colors = new Float32Array(buffer.length);
  99521. tempVertexData.colors.set(buffer);
  99522. }
  99523. }
  99524. // Indices
  99525. accessor = gltfRuntime.accessors[primitive.indices];
  99526. if (accessor) {
  99527. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  99528. tempVertexData.indices = new Int32Array(buffer.length);
  99529. tempVertexData.indices.set(buffer);
  99530. indexCounts.push(tempVertexData.indices.length);
  99531. }
  99532. else {
  99533. // Set indices on the fly
  99534. var indices = [];
  99535. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  99536. indices.push(j);
  99537. }
  99538. tempVertexData.indices = new Int32Array(indices);
  99539. indexCounts.push(tempVertexData.indices.length);
  99540. }
  99541. if (!vertexData) {
  99542. vertexData = tempVertexData;
  99543. }
  99544. else {
  99545. vertexData.merge(tempVertexData);
  99546. }
  99547. // Sub material
  99548. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  99549. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  99550. // Update vertices start and index start
  99551. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  99552. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  99553. }
  99554. }
  99555. var material;
  99556. if (subMaterials.length > 1) {
  99557. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  99558. material.subMaterials = subMaterials;
  99559. }
  99560. else {
  99561. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  99562. }
  99563. if (subMaterials.length === 1) {
  99564. material = subMaterials[0];
  99565. }
  99566. if (!newMesh.material) {
  99567. newMesh.material = material;
  99568. }
  99569. // Apply geometry
  99570. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  99571. newMesh.computeWorldMatrix(true);
  99572. // Apply submeshes
  99573. newMesh.subMeshes = [];
  99574. var index = 0;
  99575. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  99576. var meshID = meshes[meshIndex];
  99577. var mesh = gltfRuntime.meshes[meshID];
  99578. if (!mesh) {
  99579. continue;
  99580. }
  99581. for (var i = 0; i < mesh.primitives.length; i++) {
  99582. if (mesh.primitives[i].mode !== 4) {
  99583. //continue;
  99584. }
  99585. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  99586. index++;
  99587. }
  99588. }
  99589. // Finish
  99590. return newMesh;
  99591. };
  99592. /**
  99593. * Configure node transformation from position, rotation and scaling
  99594. */
  99595. var configureNode = function (newNode, position, rotation, scaling) {
  99596. if (newNode.position) {
  99597. newNode.position = position;
  99598. }
  99599. if (newNode.rotationQuaternion || newNode.rotation) {
  99600. newNode.rotationQuaternion = rotation;
  99601. }
  99602. if (newNode.scaling) {
  99603. newNode.scaling = scaling;
  99604. }
  99605. };
  99606. /**
  99607. * Configures node from transformation matrix
  99608. */
  99609. var configureNodeFromMatrix = function (newNode, node, parent) {
  99610. if (node.matrix) {
  99611. var position = new BABYLON.Vector3(0, 0, 0);
  99612. var rotation = new BABYLON.Quaternion();
  99613. var scaling = new BABYLON.Vector3(0, 0, 0);
  99614. var mat = BABYLON.Matrix.FromArray(node.matrix);
  99615. mat.decompose(scaling, rotation, position);
  99616. configureNode(newNode, position, rotation, scaling);
  99617. }
  99618. else if (node.translation && node.rotation && node.scale) {
  99619. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  99620. }
  99621. newNode.computeWorldMatrix(true);
  99622. };
  99623. /**
  99624. * Imports a node
  99625. */
  99626. var importNode = function (gltfRuntime, node, id, parent) {
  99627. var lastNode = null;
  99628. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  99629. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  99630. return null;
  99631. }
  99632. }
  99633. // Meshes
  99634. if (node.skin) {
  99635. if (node.meshes) {
  99636. var skin = gltfRuntime.skins[node.skin];
  99637. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  99638. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  99639. if (newMesh.skeleton === null) {
  99640. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  99641. if (!skin.babylonSkeleton) {
  99642. skin.babylonSkeleton = newMesh.skeleton;
  99643. }
  99644. }
  99645. lastNode = newMesh;
  99646. }
  99647. }
  99648. else if (node.meshes) {
  99649. /**
  99650. * Improve meshes property
  99651. */
  99652. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  99653. lastNode = newMesh;
  99654. }
  99655. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  99656. var light = gltfRuntime.lights[node.light];
  99657. if (light) {
  99658. if (light.type === "ambient") {
  99659. var ambienLight = light[light.type];
  99660. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  99661. hemiLight.name = node.name || "";
  99662. if (ambienLight.color) {
  99663. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  99664. }
  99665. lastNode = hemiLight;
  99666. }
  99667. else if (light.type === "directional") {
  99668. var directionalLight = light[light.type];
  99669. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  99670. dirLight.name = node.name || "";
  99671. if (directionalLight.color) {
  99672. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  99673. }
  99674. lastNode = dirLight;
  99675. }
  99676. else if (light.type === "point") {
  99677. var pointLight = light[light.type];
  99678. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  99679. ptLight.name = node.name || "";
  99680. if (pointLight.color) {
  99681. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  99682. }
  99683. lastNode = ptLight;
  99684. }
  99685. else if (light.type === "spot") {
  99686. var spotLight = light[light.type];
  99687. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  99688. spLight.name = node.name || "";
  99689. if (spotLight.color) {
  99690. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  99691. }
  99692. if (spotLight.fallOfAngle) {
  99693. spLight.angle = spotLight.fallOfAngle;
  99694. }
  99695. if (spotLight.fallOffExponent) {
  99696. spLight.exponent = spotLight.fallOffExponent;
  99697. }
  99698. lastNode = spLight;
  99699. }
  99700. }
  99701. }
  99702. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  99703. var camera = gltfRuntime.cameras[node.camera];
  99704. if (camera) {
  99705. if (camera.type === "orthographic") {
  99706. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  99707. orthoCamera.name = node.name || "";
  99708. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  99709. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  99710. lastNode = orthoCamera;
  99711. }
  99712. else if (camera.type === "perspective") {
  99713. var perspectiveCamera = camera[camera.type];
  99714. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  99715. persCamera.name = node.name || "";
  99716. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  99717. if (!perspectiveCamera.aspectRatio) {
  99718. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  99719. }
  99720. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  99721. persCamera.maxZ = perspectiveCamera.zfar;
  99722. persCamera.minZ = perspectiveCamera.znear;
  99723. }
  99724. lastNode = persCamera;
  99725. }
  99726. }
  99727. }
  99728. // Empty node
  99729. if (!node.jointName) {
  99730. if (node.babylonNode) {
  99731. return node.babylonNode;
  99732. }
  99733. else if (lastNode === null) {
  99734. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  99735. node.babylonNode = dummy;
  99736. lastNode = dummy;
  99737. }
  99738. }
  99739. if (lastNode !== null) {
  99740. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  99741. configureNodeFromMatrix(lastNode, node, parent);
  99742. }
  99743. else {
  99744. var translation = node.translation || [0, 0, 0];
  99745. var rotation = node.rotation || [0, 0, 0, 1];
  99746. var scale = node.scale || [1, 1, 1];
  99747. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  99748. }
  99749. lastNode.updateCache(true);
  99750. node.babylonNode = lastNode;
  99751. }
  99752. return lastNode;
  99753. };
  99754. /**
  99755. * Traverses nodes and creates them
  99756. */
  99757. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  99758. if (meshIncluded === void 0) { meshIncluded = false; }
  99759. var node = gltfRuntime.nodes[id];
  99760. var newNode = null;
  99761. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  99762. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  99763. meshIncluded = true;
  99764. }
  99765. else {
  99766. meshIncluded = false;
  99767. }
  99768. }
  99769. else {
  99770. meshIncluded = true;
  99771. }
  99772. if (!node.jointName && meshIncluded) {
  99773. newNode = importNode(gltfRuntime, node, id, parent);
  99774. if (newNode !== null) {
  99775. newNode.id = id;
  99776. newNode.parent = parent;
  99777. }
  99778. }
  99779. if (node.children) {
  99780. for (var i = 0; i < node.children.length; i++) {
  99781. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  99782. }
  99783. }
  99784. };
  99785. /**
  99786. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  99787. */
  99788. var postLoad = function (gltfRuntime) {
  99789. // Nodes
  99790. var currentScene = gltfRuntime.currentScene;
  99791. if (currentScene) {
  99792. for (var i = 0; i < currentScene.nodes.length; i++) {
  99793. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  99794. }
  99795. }
  99796. else {
  99797. for (var thing in gltfRuntime.scenes) {
  99798. currentScene = gltfRuntime.scenes[thing];
  99799. for (var i = 0; i < currentScene.nodes.length; i++) {
  99800. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  99801. }
  99802. }
  99803. }
  99804. // Set animations
  99805. loadAnimations(gltfRuntime);
  99806. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  99807. var skeleton = gltfRuntime.scene.skeletons[i];
  99808. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  99809. }
  99810. };
  99811. /**
  99812. * onBind shaderrs callback to set uniforms and matrices
  99813. */
  99814. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  99815. var materialValues = material.values || technique.parameters;
  99816. for (var unif in unTreatedUniforms) {
  99817. var uniform = unTreatedUniforms[unif];
  99818. var type = uniform.type;
  99819. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  99820. if (uniform.semantic && !uniform.source && !uniform.node) {
  99821. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  99822. }
  99823. else if (uniform.semantic && (uniform.source || uniform.node)) {
  99824. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  99825. if (source === null) {
  99826. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  99827. }
  99828. if (source === null) {
  99829. continue;
  99830. }
  99831. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  99832. }
  99833. }
  99834. else {
  99835. var value = materialValues[technique.uniforms[unif]];
  99836. if (!value) {
  99837. continue;
  99838. }
  99839. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  99840. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  99841. if (texture === null || texture === undefined) {
  99842. continue;
  99843. }
  99844. shaderMaterial.getEffect().setTexture(unif, texture);
  99845. }
  99846. else {
  99847. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  99848. }
  99849. }
  99850. }
  99851. onSuccess(shaderMaterial);
  99852. };
  99853. /**
  99854. * Prepare uniforms to send the only one time
  99855. * Loads the appropriate textures
  99856. */
  99857. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  99858. var materialValues = material.values || technique.parameters;
  99859. var techniqueUniforms = technique.uniforms;
  99860. /**
  99861. * Prepare values here (not matrices)
  99862. */
  99863. for (var unif in unTreatedUniforms) {
  99864. var uniform = unTreatedUniforms[unif];
  99865. var type = uniform.type;
  99866. var value = materialValues[techniqueUniforms[unif]];
  99867. if (value === undefined) {
  99868. // In case the value is the same for all materials
  99869. value = uniform.value;
  99870. }
  99871. if (!value) {
  99872. continue;
  99873. }
  99874. var onLoadTexture = function (uniformName) {
  99875. return function (texture) {
  99876. if (uniform.value && uniformName) {
  99877. // Static uniform
  99878. shaderMaterial.setTexture(uniformName, texture);
  99879. delete unTreatedUniforms[uniformName];
  99880. }
  99881. };
  99882. };
  99883. // Texture (sampler2D)
  99884. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  99885. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  99886. }
  99887. else {
  99888. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  99889. // Static uniform
  99890. delete unTreatedUniforms[unif];
  99891. }
  99892. }
  99893. }
  99894. };
  99895. /**
  99896. * Shader compilation failed
  99897. */
  99898. var onShaderCompileError = function (program, shaderMaterial, onError) {
  99899. return function (effect, error) {
  99900. shaderMaterial.dispose(true);
  99901. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  99902. };
  99903. };
  99904. /**
  99905. * Shader compilation success
  99906. */
  99907. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  99908. return function (_) {
  99909. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  99910. shaderMaterial.onBind = function (mesh) {
  99911. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  99912. };
  99913. };
  99914. };
  99915. /**
  99916. * Returns the appropriate uniform if already handled by babylon
  99917. */
  99918. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  99919. for (var unif in technique.uniforms) {
  99920. var uniform = technique.uniforms[unif];
  99921. var uniformParameter = technique.parameters[uniform];
  99922. if (tokenizer.currentIdentifier === unif) {
  99923. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  99924. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  99925. if (transformIndex !== -1) {
  99926. delete unTreatedUniforms[unif];
  99927. return babylonTransforms[transformIndex];
  99928. }
  99929. }
  99930. }
  99931. }
  99932. return tokenizer.currentIdentifier;
  99933. };
  99934. /**
  99935. * All shaders loaded. Create materials one by one
  99936. */
  99937. var importMaterials = function (gltfRuntime) {
  99938. // Create materials
  99939. for (var mat in gltfRuntime.materials) {
  99940. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  99941. }
  99942. };
  99943. /**
  99944. * Implementation of the base glTF spec
  99945. */
  99946. var GLTFLoaderBase = /** @class */ (function () {
  99947. function GLTFLoaderBase() {
  99948. }
  99949. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  99950. var gltfRuntime = {
  99951. extensions: {},
  99952. accessors: {},
  99953. buffers: {},
  99954. bufferViews: {},
  99955. meshes: {},
  99956. lights: {},
  99957. cameras: {},
  99958. nodes: {},
  99959. images: {},
  99960. textures: {},
  99961. shaders: {},
  99962. programs: {},
  99963. samplers: {},
  99964. techniques: {},
  99965. materials: {},
  99966. animations: {},
  99967. skins: {},
  99968. extensionsUsed: [],
  99969. scenes: {},
  99970. buffersCount: 0,
  99971. shaderscount: 0,
  99972. scene: scene,
  99973. rootUrl: rootUrl,
  99974. loadedBufferCount: 0,
  99975. loadedBufferViews: {},
  99976. loadedShaderCount: 0,
  99977. importOnlyMeshes: false,
  99978. dummyNodes: []
  99979. };
  99980. // Parse
  99981. if (parsedData.extensions) {
  99982. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  99983. }
  99984. if (parsedData.extensionsUsed) {
  99985. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  99986. }
  99987. if (parsedData.buffers) {
  99988. parseBuffers(parsedData.buffers, gltfRuntime);
  99989. }
  99990. if (parsedData.bufferViews) {
  99991. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  99992. }
  99993. if (parsedData.accessors) {
  99994. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  99995. }
  99996. if (parsedData.meshes) {
  99997. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  99998. }
  99999. if (parsedData.lights) {
  100000. parseObject(parsedData.lights, "lights", gltfRuntime);
  100001. }
  100002. if (parsedData.cameras) {
  100003. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  100004. }
  100005. if (parsedData.nodes) {
  100006. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  100007. }
  100008. if (parsedData.images) {
  100009. parseObject(parsedData.images, "images", gltfRuntime);
  100010. }
  100011. if (parsedData.textures) {
  100012. parseObject(parsedData.textures, "textures", gltfRuntime);
  100013. }
  100014. if (parsedData.shaders) {
  100015. parseShaders(parsedData.shaders, gltfRuntime);
  100016. }
  100017. if (parsedData.programs) {
  100018. parseObject(parsedData.programs, "programs", gltfRuntime);
  100019. }
  100020. if (parsedData.samplers) {
  100021. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  100022. }
  100023. if (parsedData.techniques) {
  100024. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  100025. }
  100026. if (parsedData.materials) {
  100027. parseObject(parsedData.materials, "materials", gltfRuntime);
  100028. }
  100029. if (parsedData.animations) {
  100030. parseObject(parsedData.animations, "animations", gltfRuntime);
  100031. }
  100032. if (parsedData.skins) {
  100033. parseObject(parsedData.skins, "skins", gltfRuntime);
  100034. }
  100035. if (parsedData.scenes) {
  100036. gltfRuntime.scenes = parsedData.scenes;
  100037. }
  100038. if (parsedData.scene && parsedData.scenes) {
  100039. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  100040. }
  100041. return gltfRuntime;
  100042. };
  100043. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  100044. var buffer = gltfRuntime.buffers[id];
  100045. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  100046. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  100047. }
  100048. else {
  100049. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  100050. if (request) {
  100051. onError(request.status + " " + request.statusText);
  100052. }
  100053. });
  100054. }
  100055. };
  100056. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  100057. var texture = gltfRuntime.textures[id];
  100058. if (!texture || !texture.source) {
  100059. onError("");
  100060. return;
  100061. }
  100062. if (texture.babylonTexture) {
  100063. onSuccess(null);
  100064. return;
  100065. }
  100066. var source = gltfRuntime.images[texture.source];
  100067. if (BABYLON.Tools.IsBase64(source.uri)) {
  100068. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  100069. }
  100070. else {
  100071. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  100072. if (request) {
  100073. onError(request.status + " " + request.statusText);
  100074. }
  100075. });
  100076. }
  100077. };
  100078. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  100079. var texture = gltfRuntime.textures[id];
  100080. if (texture.babylonTexture) {
  100081. onSuccess(texture.babylonTexture);
  100082. return;
  100083. }
  100084. var sampler = gltfRuntime.samplers[texture.sampler];
  100085. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  100086. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  100087. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  100088. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  100089. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  100090. var blob = new Blob([buffer]);
  100091. var blobURL = URL.createObjectURL(blob);
  100092. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  100093. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  100094. if (sampler.wrapS !== undefined) {
  100095. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  100096. }
  100097. if (sampler.wrapT !== undefined) {
  100098. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  100099. }
  100100. newTexture.name = id;
  100101. texture.babylonTexture = newTexture;
  100102. onSuccess(newTexture);
  100103. };
  100104. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  100105. var shader = gltfRuntime.shaders[id];
  100106. if (BABYLON.Tools.IsBase64(shader.uri)) {
  100107. var shaderString = atob(shader.uri.split(",")[1]);
  100108. if (onSuccess) {
  100109. onSuccess(shaderString);
  100110. }
  100111. }
  100112. else {
  100113. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  100114. if (request && onError) {
  100115. onError(request.status + " " + request.statusText);
  100116. }
  100117. });
  100118. }
  100119. };
  100120. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  100121. var material = gltfRuntime.materials[id];
  100122. if (!material.technique) {
  100123. if (onError) {
  100124. onError("No technique found.");
  100125. }
  100126. return;
  100127. }
  100128. var technique = gltfRuntime.techniques[material.technique];
  100129. if (!technique) {
  100130. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  100131. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  100132. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  100133. onSuccess(defaultMaterial);
  100134. return;
  100135. }
  100136. var program = gltfRuntime.programs[technique.program];
  100137. var states = technique.states;
  100138. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  100139. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  100140. var newVertexShader = "";
  100141. var newPixelShader = "";
  100142. var vertexTokenizer = new Tokenizer(vertexShader);
  100143. var pixelTokenizer = new Tokenizer(pixelShader);
  100144. var unTreatedUniforms = {};
  100145. var uniforms = [];
  100146. var attributes = [];
  100147. var samplers = [];
  100148. // Fill uniform, sampler2D and attributes
  100149. for (var unif in technique.uniforms) {
  100150. var uniform = technique.uniforms[unif];
  100151. var uniformParameter = technique.parameters[uniform];
  100152. unTreatedUniforms[unif] = uniformParameter;
  100153. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  100154. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  100155. if (transformIndex !== -1) {
  100156. uniforms.push(babylonTransforms[transformIndex]);
  100157. delete unTreatedUniforms[unif];
  100158. }
  100159. else {
  100160. uniforms.push(unif);
  100161. }
  100162. }
  100163. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  100164. samplers.push(unif);
  100165. }
  100166. else {
  100167. uniforms.push(unif);
  100168. }
  100169. }
  100170. for (var attr in technique.attributes) {
  100171. var attribute = technique.attributes[attr];
  100172. var attributeParameter = technique.parameters[attribute];
  100173. if (attributeParameter.semantic) {
  100174. attributes.push(getAttribute(attributeParameter));
  100175. }
  100176. }
  100177. // Configure vertex shader
  100178. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  100179. var tokenType = vertexTokenizer.currentToken;
  100180. if (tokenType !== ETokenType.IDENTIFIER) {
  100181. newVertexShader += vertexTokenizer.currentString;
  100182. continue;
  100183. }
  100184. var foundAttribute = false;
  100185. for (var attr in technique.attributes) {
  100186. var attribute = technique.attributes[attr];
  100187. var attributeParameter = technique.parameters[attribute];
  100188. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  100189. newVertexShader += getAttribute(attributeParameter);
  100190. foundAttribute = true;
  100191. break;
  100192. }
  100193. }
  100194. if (foundAttribute) {
  100195. continue;
  100196. }
  100197. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  100198. }
  100199. // Configure pixel shader
  100200. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  100201. var tokenType = pixelTokenizer.currentToken;
  100202. if (tokenType !== ETokenType.IDENTIFIER) {
  100203. newPixelShader += pixelTokenizer.currentString;
  100204. continue;
  100205. }
  100206. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  100207. }
  100208. // Create shader material
  100209. var shaderPath = {
  100210. vertex: program.vertexShader + id,
  100211. fragment: program.fragmentShader + id
  100212. };
  100213. var options = {
  100214. attributes: attributes,
  100215. uniforms: uniforms,
  100216. samplers: samplers,
  100217. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  100218. };
  100219. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  100220. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  100221. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  100222. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  100223. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  100224. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  100225. if (states && states.functions) {
  100226. var functions = states.functions;
  100227. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  100228. shaderMaterial.backFaceCulling = false;
  100229. }
  100230. var blendFunc = functions.blendFuncSeparate;
  100231. if (blendFunc) {
  100232. 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) {
  100233. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  100234. }
  100235. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  100236. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  100237. }
  100238. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  100239. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  100240. }
  100241. 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) {
  100242. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  100243. }
  100244. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  100245. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  100246. }
  100247. 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) {
  100248. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  100249. }
  100250. }
  100251. }
  100252. };
  100253. return GLTFLoaderBase;
  100254. }());
  100255. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  100256. /**
  100257. * glTF V1 Loader
  100258. */
  100259. var GLTFLoader = /** @class */ (function () {
  100260. function GLTFLoader() {
  100261. // #region Stubs for IGLTFLoader interface
  100262. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  100263. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  100264. this.compileMaterials = false;
  100265. this.useClipPlane = false;
  100266. this.compileShadowGenerators = false;
  100267. this.onDisposeObservable = new BABYLON.Observable();
  100268. this.onMeshLoadedObservable = new BABYLON.Observable();
  100269. this.onTextureLoadedObservable = new BABYLON.Observable();
  100270. this.onMaterialLoadedObservable = new BABYLON.Observable();
  100271. this.onCompleteObservable = new BABYLON.Observable();
  100272. this.onExtensionLoadedObservable = new BABYLON.Observable();
  100273. this.state = null;
  100274. }
  100275. GLTFLoader.RegisterExtension = function (extension) {
  100276. if (GLTFLoader.Extensions[extension.name]) {
  100277. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  100278. return;
  100279. }
  100280. GLTFLoader.Extensions[extension.name] = extension;
  100281. };
  100282. GLTFLoader.prototype.dispose = function () { };
  100283. // #endregion
  100284. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  100285. var _this = this;
  100286. scene.useRightHandedSystem = true;
  100287. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  100288. gltfRuntime.importOnlyMeshes = true;
  100289. if (meshesNames === "") {
  100290. gltfRuntime.importMeshesNames = [];
  100291. }
  100292. else if (typeof meshesNames === "string") {
  100293. gltfRuntime.importMeshesNames = [meshesNames];
  100294. }
  100295. else if (meshesNames && !(meshesNames instanceof Array)) {
  100296. gltfRuntime.importMeshesNames = [meshesNames];
  100297. }
  100298. else {
  100299. gltfRuntime.importMeshesNames = [];
  100300. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  100301. }
  100302. // Create nodes
  100303. _this._createNodes(gltfRuntime);
  100304. var meshes = new Array();
  100305. var skeletons = new Array();
  100306. // Fill arrays of meshes and skeletons
  100307. for (var nde in gltfRuntime.nodes) {
  100308. var node = gltfRuntime.nodes[nde];
  100309. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  100310. meshes.push(node.babylonNode);
  100311. }
  100312. }
  100313. for (var skl in gltfRuntime.skins) {
  100314. var skin = gltfRuntime.skins[skl];
  100315. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  100316. skeletons.push(skin.babylonSkeleton);
  100317. }
  100318. }
  100319. // Load buffers, shaders, materials, etc.
  100320. _this._loadBuffersAsync(gltfRuntime, function () {
  100321. _this._loadShadersAsync(gltfRuntime, function () {
  100322. importMaterials(gltfRuntime);
  100323. postLoad(gltfRuntime);
  100324. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  100325. onSuccess(meshes, skeletons);
  100326. }
  100327. });
  100328. }, onProgress);
  100329. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  100330. onSuccess(meshes, skeletons);
  100331. }
  100332. }, onError);
  100333. return true;
  100334. };
  100335. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  100336. var _this = this;
  100337. return new Promise(function (resolve, reject) {
  100338. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  100339. resolve({
  100340. meshes: meshes,
  100341. particleSystems: [],
  100342. skeletons: skeletons,
  100343. animationGroups: []
  100344. });
  100345. }, onProgress, function (message) {
  100346. reject(new Error(message));
  100347. });
  100348. });
  100349. };
  100350. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  100351. var _this = this;
  100352. scene.useRightHandedSystem = true;
  100353. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  100354. // Load runtime extensios
  100355. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  100356. // Create nodes
  100357. _this._createNodes(gltfRuntime);
  100358. // Load buffers, shaders, materials, etc.
  100359. _this._loadBuffersAsync(gltfRuntime, function () {
  100360. _this._loadShadersAsync(gltfRuntime, function () {
  100361. importMaterials(gltfRuntime);
  100362. postLoad(gltfRuntime);
  100363. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  100364. onSuccess();
  100365. }
  100366. });
  100367. });
  100368. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  100369. onSuccess();
  100370. }
  100371. }, onError);
  100372. }, onError);
  100373. };
  100374. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  100375. var _this = this;
  100376. return new Promise(function (resolve, reject) {
  100377. _this._loadAsync(scene, data, rootUrl, function () {
  100378. resolve();
  100379. }, onProgress, function (message) {
  100380. reject(new Error(message));
  100381. });
  100382. });
  100383. };
  100384. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  100385. var hasShaders = false;
  100386. var processShader = function (sha, shader) {
  100387. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  100388. if (shaderString instanceof ArrayBuffer) {
  100389. return;
  100390. }
  100391. gltfRuntime.loadedShaderCount++;
  100392. if (shaderString) {
  100393. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  100394. }
  100395. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  100396. onload();
  100397. }
  100398. }, function () {
  100399. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  100400. });
  100401. };
  100402. for (var sha in gltfRuntime.shaders) {
  100403. hasShaders = true;
  100404. var shader = gltfRuntime.shaders[sha];
  100405. if (shader) {
  100406. processShader.bind(this, sha, shader)();
  100407. }
  100408. else {
  100409. BABYLON.Tools.Error("No shader named: " + sha);
  100410. }
  100411. }
  100412. if (!hasShaders) {
  100413. onload();
  100414. }
  100415. };
  100416. ;
  100417. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  100418. var hasBuffers = false;
  100419. var processBuffer = function (buf, buffer) {
  100420. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  100421. gltfRuntime.loadedBufferCount++;
  100422. if (bufferView) {
  100423. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  100424. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  100425. }
  100426. gltfRuntime.loadedBufferViews[buf] = bufferView;
  100427. }
  100428. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  100429. onLoad();
  100430. }
  100431. }, function () {
  100432. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  100433. });
  100434. };
  100435. for (var buf in gltfRuntime.buffers) {
  100436. hasBuffers = true;
  100437. var buffer = gltfRuntime.buffers[buf];
  100438. if (buffer) {
  100439. processBuffer.bind(this, buf, buffer)();
  100440. }
  100441. else {
  100442. BABYLON.Tools.Error("No buffer named: " + buf);
  100443. }
  100444. }
  100445. if (!hasBuffers) {
  100446. onLoad();
  100447. }
  100448. };
  100449. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  100450. var currentScene = gltfRuntime.currentScene;
  100451. if (currentScene) {
  100452. // Only one scene even if multiple scenes are defined
  100453. for (var i = 0; i < currentScene.nodes.length; i++) {
  100454. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  100455. }
  100456. }
  100457. else {
  100458. // Load all scenes
  100459. for (var thing in gltfRuntime.scenes) {
  100460. currentScene = gltfRuntime.scenes[thing];
  100461. for (var i = 0; i < currentScene.nodes.length; i++) {
  100462. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  100463. }
  100464. }
  100465. }
  100466. };
  100467. GLTFLoader.Extensions = {};
  100468. return GLTFLoader;
  100469. }());
  100470. GLTF1.GLTFLoader = GLTFLoader;
  100471. ;
  100472. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  100473. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  100474. })(BABYLON || (BABYLON = {}));
  100475. //# sourceMappingURL=babylon.glTFLoader.js.map
  100476. "use strict";
  100477. var BABYLON;
  100478. (function (BABYLON) {
  100479. var GLTF1;
  100480. (function (GLTF1) {
  100481. /**
  100482. * Utils functions for GLTF
  100483. */
  100484. var GLTFUtils = /** @class */ (function () {
  100485. function GLTFUtils() {
  100486. }
  100487. /**
  100488. * Sets the given "parameter" matrix
  100489. * @param scene: the {BABYLON.Scene} object
  100490. * @param source: the source node where to pick the matrix
  100491. * @param parameter: the GLTF technique parameter
  100492. * @param uniformName: the name of the shader's uniform
  100493. * @param shaderMaterial: the shader material
  100494. */
  100495. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  100496. var mat = null;
  100497. if (parameter.semantic === "MODEL") {
  100498. mat = source.getWorldMatrix();
  100499. }
  100500. else if (parameter.semantic === "PROJECTION") {
  100501. mat = scene.getProjectionMatrix();
  100502. }
  100503. else if (parameter.semantic === "VIEW") {
  100504. mat = scene.getViewMatrix();
  100505. }
  100506. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  100507. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  100508. }
  100509. else if (parameter.semantic === "MODELVIEW") {
  100510. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  100511. }
  100512. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  100513. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  100514. }
  100515. else if (parameter.semantic === "MODELINVERSE") {
  100516. mat = source.getWorldMatrix().invert();
  100517. }
  100518. else if (parameter.semantic === "VIEWINVERSE") {
  100519. mat = scene.getViewMatrix().invert();
  100520. }
  100521. else if (parameter.semantic === "PROJECTIONINVERSE") {
  100522. mat = scene.getProjectionMatrix().invert();
  100523. }
  100524. else if (parameter.semantic === "MODELVIEWINVERSE") {
  100525. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  100526. }
  100527. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  100528. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  100529. }
  100530. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  100531. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  100532. }
  100533. else {
  100534. debugger;
  100535. }
  100536. if (mat) {
  100537. switch (parameter.type) {
  100538. case GLTF1.EParameterType.FLOAT_MAT2:
  100539. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  100540. break;
  100541. case GLTF1.EParameterType.FLOAT_MAT3:
  100542. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  100543. break;
  100544. case GLTF1.EParameterType.FLOAT_MAT4:
  100545. shaderMaterial.setMatrix(uniformName, mat);
  100546. break;
  100547. default: break;
  100548. }
  100549. }
  100550. };
  100551. /**
  100552. * Sets the given "parameter" matrix
  100553. * @param shaderMaterial: the shader material
  100554. * @param uniform: the name of the shader's uniform
  100555. * @param value: the value of the uniform
  100556. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  100557. */
  100558. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  100559. switch (type) {
  100560. case GLTF1.EParameterType.FLOAT:
  100561. shaderMaterial.setFloat(uniform, value);
  100562. return true;
  100563. case GLTF1.EParameterType.FLOAT_VEC2:
  100564. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  100565. return true;
  100566. case GLTF1.EParameterType.FLOAT_VEC3:
  100567. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  100568. return true;
  100569. case GLTF1.EParameterType.FLOAT_VEC4:
  100570. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  100571. return true;
  100572. default: return false;
  100573. }
  100574. };
  100575. /**
  100576. * Returns the wrap mode of the texture
  100577. * @param mode: the mode value
  100578. */
  100579. GLTFUtils.GetWrapMode = function (mode) {
  100580. switch (mode) {
  100581. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  100582. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  100583. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  100584. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  100585. }
  100586. };
  100587. /**
  100588. * Returns the byte stride giving an accessor
  100589. * @param accessor: the GLTF accessor objet
  100590. */
  100591. GLTFUtils.GetByteStrideFromType = function (accessor) {
  100592. // Needs this function since "byteStride" isn't requiered in glTF format
  100593. var type = accessor.type;
  100594. switch (type) {
  100595. case "VEC2": return 2;
  100596. case "VEC3": return 3;
  100597. case "VEC4": return 4;
  100598. case "MAT2": return 4;
  100599. case "MAT3": return 9;
  100600. case "MAT4": return 16;
  100601. default: return 1;
  100602. }
  100603. };
  100604. /**
  100605. * Returns the texture filter mode giving a mode value
  100606. * @param mode: the filter mode value
  100607. */
  100608. GLTFUtils.GetTextureFilterMode = function (mode) {
  100609. switch (mode) {
  100610. case GLTF1.ETextureFilterType.LINEAR:
  100611. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  100612. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100613. case GLTF1.ETextureFilterType.NEAREST:
  100614. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  100615. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  100616. }
  100617. };
  100618. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  100619. var byteOffset = bufferView.byteOffset + byteOffset;
  100620. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  100621. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  100622. throw new Error("Buffer access is out of range");
  100623. }
  100624. var buffer = loadedBufferView.buffer;
  100625. byteOffset += loadedBufferView.byteOffset;
  100626. switch (componentType) {
  100627. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  100628. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  100629. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  100630. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  100631. default: return new Float32Array(buffer, byteOffset, byteLength);
  100632. }
  100633. };
  100634. /**
  100635. * Returns a buffer from its accessor
  100636. * @param gltfRuntime: the GLTF runtime
  100637. * @param accessor: the GLTF accessor
  100638. */
  100639. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  100640. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  100641. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  100642. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  100643. };
  100644. /**
  100645. * Decodes a buffer view into a string
  100646. * @param view: the buffer view
  100647. */
  100648. GLTFUtils.DecodeBufferToText = function (view) {
  100649. var result = "";
  100650. var length = view.byteLength;
  100651. for (var i = 0; i < length; ++i) {
  100652. result += String.fromCharCode(view[i]);
  100653. }
  100654. return result;
  100655. };
  100656. /**
  100657. * Returns the default material of gltf. Related to
  100658. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  100659. * @param scene: the Babylon.js scene
  100660. */
  100661. GLTFUtils.GetDefaultMaterial = function (scene) {
  100662. if (!GLTFUtils._DefaultMaterial) {
  100663. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  100664. "precision highp float;",
  100665. "",
  100666. "uniform mat4 worldView;",
  100667. "uniform mat4 projection;",
  100668. "",
  100669. "attribute vec3 position;",
  100670. "",
  100671. "void main(void)",
  100672. "{",
  100673. " gl_Position = projection * worldView * vec4(position, 1.0);",
  100674. "}"
  100675. ].join("\n");
  100676. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  100677. "precision highp float;",
  100678. "",
  100679. "uniform vec4 u_emission;",
  100680. "",
  100681. "void main(void)",
  100682. "{",
  100683. " gl_FragColor = u_emission;",
  100684. "}"
  100685. ].join("\n");
  100686. var shaderPath = {
  100687. vertex: "GLTFDefaultMaterial",
  100688. fragment: "GLTFDefaultMaterial"
  100689. };
  100690. var options = {
  100691. attributes: ["position"],
  100692. uniforms: ["worldView", "projection", "u_emission"],
  100693. samplers: new Array(),
  100694. needAlphaBlending: false
  100695. };
  100696. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  100697. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  100698. }
  100699. return GLTFUtils._DefaultMaterial;
  100700. };
  100701. // The GLTF default material
  100702. GLTFUtils._DefaultMaterial = null;
  100703. return GLTFUtils;
  100704. }());
  100705. GLTF1.GLTFUtils = GLTFUtils;
  100706. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  100707. })(BABYLON || (BABYLON = {}));
  100708. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  100709. "use strict";
  100710. var BABYLON;
  100711. (function (BABYLON) {
  100712. var GLTF1;
  100713. (function (GLTF1) {
  100714. var GLTFLoaderExtension = /** @class */ (function () {
  100715. function GLTFLoaderExtension(name) {
  100716. this._name = name;
  100717. }
  100718. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  100719. get: function () {
  100720. return this._name;
  100721. },
  100722. enumerable: true,
  100723. configurable: true
  100724. });
  100725. /**
  100726. * Defines an override for loading the runtime
  100727. * Return true to stop further extensions from loading the runtime
  100728. */
  100729. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  100730. return false;
  100731. };
  100732. /**
  100733. * Defines an onverride for creating gltf runtime
  100734. * Return true to stop further extensions from creating the runtime
  100735. */
  100736. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  100737. return false;
  100738. };
  100739. /**
  100740. * Defines an override for loading buffers
  100741. * Return true to stop further extensions from loading this buffer
  100742. */
  100743. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  100744. return false;
  100745. };
  100746. /**
  100747. * Defines an override for loading texture buffers
  100748. * Return true to stop further extensions from loading this texture data
  100749. */
  100750. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  100751. return false;
  100752. };
  100753. /**
  100754. * Defines an override for creating textures
  100755. * Return true to stop further extensions from loading this texture
  100756. */
  100757. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  100758. return false;
  100759. };
  100760. /**
  100761. * Defines an override for loading shader strings
  100762. * Return true to stop further extensions from loading this shader data
  100763. */
  100764. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  100765. return false;
  100766. };
  100767. /**
  100768. * Defines an override for loading materials
  100769. * Return true to stop further extensions from loading this material
  100770. */
  100771. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  100772. return false;
  100773. };
  100774. // ---------
  100775. // Utilities
  100776. // ---------
  100777. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  100778. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100779. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  100780. }, function () {
  100781. setTimeout(function () {
  100782. if (!onSuccess) {
  100783. return;
  100784. }
  100785. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  100786. });
  100787. });
  100788. };
  100789. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  100790. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100791. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  100792. }, function () {
  100793. setTimeout(function () {
  100794. onSuccess();
  100795. });
  100796. });
  100797. };
  100798. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  100799. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100800. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  100801. }, function () {
  100802. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  100803. });
  100804. };
  100805. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  100806. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  100807. if (buffer) {
  100808. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  100809. }
  100810. }, onError);
  100811. };
  100812. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  100813. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100814. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  100815. }, function () {
  100816. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  100817. });
  100818. };
  100819. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  100820. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100821. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  100822. }, function () {
  100823. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  100824. });
  100825. };
  100826. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  100827. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100828. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  100829. }, function () {
  100830. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  100831. });
  100832. };
  100833. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  100834. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  100835. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  100836. }, function () {
  100837. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  100838. });
  100839. };
  100840. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  100841. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  100842. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  100843. if (func(loaderExtension)) {
  100844. return;
  100845. }
  100846. }
  100847. defaultFunc();
  100848. };
  100849. return GLTFLoaderExtension;
  100850. }());
  100851. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  100852. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  100853. })(BABYLON || (BABYLON = {}));
  100854. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  100855. "use strict";
  100856. var BABYLON;
  100857. (function (BABYLON) {
  100858. var GLTF1;
  100859. (function (GLTF1) {
  100860. var BinaryExtensionBufferName = "binary_glTF";
  100861. ;
  100862. ;
  100863. var GLTFBinaryExtension = /** @class */ (function (_super) {
  100864. __extends(GLTFBinaryExtension, _super);
  100865. function GLTFBinaryExtension() {
  100866. return _super.call(this, "KHR_binary_glTF") || this;
  100867. }
  100868. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  100869. var extensionsUsed = data.json.extensionsUsed;
  100870. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  100871. return false;
  100872. }
  100873. this._bin = data.bin;
  100874. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  100875. return true;
  100876. };
  100877. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  100878. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  100879. return false;
  100880. }
  100881. if (id !== BinaryExtensionBufferName) {
  100882. return false;
  100883. }
  100884. onSuccess(this._bin);
  100885. return true;
  100886. };
  100887. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  100888. var texture = gltfRuntime.textures[id];
  100889. var source = gltfRuntime.images[texture.source];
  100890. if (!source.extensions || !(this.name in source.extensions)) {
  100891. return false;
  100892. }
  100893. var sourceExt = source.extensions[this.name];
  100894. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  100895. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  100896. onSuccess(buffer);
  100897. return true;
  100898. };
  100899. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  100900. var shader = gltfRuntime.shaders[id];
  100901. if (!shader.extensions || !(this.name in shader.extensions)) {
  100902. return false;
  100903. }
  100904. var binaryExtensionShader = shader.extensions[this.name];
  100905. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  100906. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  100907. setTimeout(function () {
  100908. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  100909. onSuccess(shaderString);
  100910. });
  100911. return true;
  100912. };
  100913. return GLTFBinaryExtension;
  100914. }(GLTF1.GLTFLoaderExtension));
  100915. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  100916. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  100917. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  100918. })(BABYLON || (BABYLON = {}));
  100919. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  100920. "use strict";
  100921. var BABYLON;
  100922. (function (BABYLON) {
  100923. var GLTF1;
  100924. (function (GLTF1) {
  100925. ;
  100926. ;
  100927. ;
  100928. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  100929. __extends(GLTFMaterialsCommonExtension, _super);
  100930. function GLTFMaterialsCommonExtension() {
  100931. return _super.call(this, "KHR_materials_common") || this;
  100932. }
  100933. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  100934. if (!gltfRuntime.extensions)
  100935. return false;
  100936. var extension = gltfRuntime.extensions[this.name];
  100937. if (!extension)
  100938. return false;
  100939. // Create lights
  100940. var lights = extension.lights;
  100941. if (lights) {
  100942. for (var thing in lights) {
  100943. var light = lights[thing];
  100944. switch (light.type) {
  100945. case "ambient":
  100946. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  100947. var ambient = light.ambient;
  100948. if (ambient) {
  100949. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  100950. }
  100951. break;
  100952. case "point":
  100953. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  100954. var point = light.point;
  100955. if (point) {
  100956. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  100957. }
  100958. break;
  100959. case "directional":
  100960. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  100961. var directional = light.directional;
  100962. if (directional) {
  100963. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  100964. }
  100965. break;
  100966. case "spot":
  100967. var spot = light.spot;
  100968. if (spot) {
  100969. 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);
  100970. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  100971. }
  100972. break;
  100973. default:
  100974. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  100975. break;
  100976. }
  100977. }
  100978. }
  100979. return false;
  100980. };
  100981. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  100982. var material = gltfRuntime.materials[id];
  100983. if (!material || !material.extensions)
  100984. return false;
  100985. var extension = material.extensions[this.name];
  100986. if (!extension)
  100987. return false;
  100988. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  100989. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  100990. if (extension.technique === "CONSTANT") {
  100991. standardMaterial.disableLighting = true;
  100992. }
  100993. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  100994. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  100995. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  100996. // Ambient
  100997. if (typeof extension.values.ambient === "string") {
  100998. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  100999. }
  101000. else {
  101001. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  101002. }
  101003. // Diffuse
  101004. if (typeof extension.values.diffuse === "string") {
  101005. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  101006. }
  101007. else {
  101008. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  101009. }
  101010. // Emission
  101011. if (typeof extension.values.emission === "string") {
  101012. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  101013. }
  101014. else {
  101015. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  101016. }
  101017. // Specular
  101018. if (typeof extension.values.specular === "string") {
  101019. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  101020. }
  101021. else {
  101022. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  101023. }
  101024. return true;
  101025. };
  101026. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  101027. // Create buffer from texture url
  101028. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  101029. // Create texture from buffer
  101030. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  101031. }, onError);
  101032. };
  101033. return GLTFMaterialsCommonExtension;
  101034. }(GLTF1.GLTFLoaderExtension));
  101035. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  101036. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  101037. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  101038. })(BABYLON || (BABYLON = {}));
  101039. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  101040. "use strict";
  101041. var BABYLON;
  101042. (function (BABYLON) {
  101043. var GLTF2;
  101044. (function (GLTF2) {
  101045. var ArrayItem = /** @class */ (function () {
  101046. function ArrayItem() {
  101047. }
  101048. ArrayItem.Assign = function (values) {
  101049. if (values) {
  101050. for (var index = 0; index < values.length; index++) {
  101051. values[index]._index = index;
  101052. }
  101053. }
  101054. };
  101055. return ArrayItem;
  101056. }());
  101057. GLTF2.ArrayItem = ArrayItem;
  101058. var AnimationMultiTarget = /** @class */ (function () {
  101059. function AnimationMultiTarget() {
  101060. this.subTargets = new Array();
  101061. }
  101062. Object.defineProperty(AnimationMultiTarget.prototype, "position", {
  101063. set: function (value) {
  101064. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  101065. var subTarget = _a[_i];
  101066. subTarget.position = value;
  101067. }
  101068. },
  101069. enumerable: true,
  101070. configurable: true
  101071. });
  101072. Object.defineProperty(AnimationMultiTarget.prototype, "rotationQuaternion", {
  101073. set: function (value) {
  101074. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  101075. var subTarget = _a[_i];
  101076. subTarget.rotationQuaternion = value;
  101077. }
  101078. },
  101079. enumerable: true,
  101080. configurable: true
  101081. });
  101082. Object.defineProperty(AnimationMultiTarget.prototype, "scaling", {
  101083. set: function (value) {
  101084. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  101085. var subTarget = _a[_i];
  101086. subTarget.scaling = value;
  101087. }
  101088. },
  101089. enumerable: true,
  101090. configurable: true
  101091. });
  101092. Object.defineProperty(AnimationMultiTarget.prototype, "influence", {
  101093. set: function (value) {
  101094. for (var _i = 0, _a = this.subTargets; _i < _a.length; _i++) {
  101095. var subTarget = _a[_i];
  101096. subTarget.influence = value;
  101097. }
  101098. },
  101099. enumerable: true,
  101100. configurable: true
  101101. });
  101102. return AnimationMultiTarget;
  101103. }());
  101104. GLTF2.AnimationMultiTarget = AnimationMultiTarget;
  101105. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  101106. })(BABYLON || (BABYLON = {}));
  101107. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  101108. "use strict";
  101109. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  101110. "use strict";
  101111. var BABYLON;
  101112. (function (BABYLON) {
  101113. var GLTF2;
  101114. (function (GLTF2) {
  101115. var GLTFLoader = /** @class */ (function () {
  101116. function GLTFLoader() {
  101117. this._completePromises = new Array();
  101118. this._disposed = false;
  101119. this._state = null;
  101120. this._extensions = {};
  101121. this._defaultSampler = {};
  101122. this._defaultBabylonMaterials = {};
  101123. this._requests = new Array();
  101124. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  101125. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  101126. this.compileMaterials = false;
  101127. this.useClipPlane = false;
  101128. this.compileShadowGenerators = false;
  101129. this.onDisposeObservable = new BABYLON.Observable();
  101130. this.onMeshLoadedObservable = new BABYLON.Observable();
  101131. this.onTextureLoadedObservable = new BABYLON.Observable();
  101132. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101133. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101134. this.onCompleteObservable = new BABYLON.Observable();
  101135. }
  101136. GLTFLoader._Register = function (name, factory) {
  101137. if (GLTFLoader._Factories[name]) {
  101138. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  101139. return;
  101140. }
  101141. GLTFLoader._Factories[name] = factory;
  101142. // Keep the order of registration so that extensions registered first are called first.
  101143. GLTFLoader._Names.push(name);
  101144. };
  101145. Object.defineProperty(GLTFLoader.prototype, "state", {
  101146. get: function () {
  101147. return this._state;
  101148. },
  101149. enumerable: true,
  101150. configurable: true
  101151. });
  101152. GLTFLoader.prototype.dispose = function () {
  101153. if (this._disposed) {
  101154. return;
  101155. }
  101156. this._disposed = true;
  101157. this.onDisposeObservable.notifyObservers(this);
  101158. this.onDisposeObservable.clear();
  101159. this._clear();
  101160. };
  101161. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  101162. var _this = this;
  101163. return Promise.resolve().then(function () {
  101164. var nodes = null;
  101165. if (meshesNames) {
  101166. var nodeMap_1 = {};
  101167. if (_this._gltf.nodes) {
  101168. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  101169. var node = _a[_i];
  101170. if (node.name) {
  101171. nodeMap_1[node.name] = node;
  101172. }
  101173. }
  101174. }
  101175. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  101176. nodes = names.map(function (name) {
  101177. var node = nodeMap_1[name];
  101178. if (!node) {
  101179. throw new Error("Failed to find node '" + name + "'");
  101180. }
  101181. return node;
  101182. });
  101183. }
  101184. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  101185. return {
  101186. meshes: _this._getMeshes(),
  101187. particleSystems: [],
  101188. skeletons: _this._getSkeletons(),
  101189. animationGroups: _this._getAnimationGroups()
  101190. };
  101191. });
  101192. });
  101193. };
  101194. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  101195. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  101196. };
  101197. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  101198. var _this = this;
  101199. return Promise.resolve().then(function () {
  101200. _this._loadExtensions();
  101201. _this._babylonScene = scene;
  101202. _this._rootUrl = rootUrl;
  101203. _this._progressCallback = onProgress;
  101204. _this._state = BABYLON.GLTFLoaderState.Loading;
  101205. _this._loadData(data);
  101206. _this._checkExtensions();
  101207. var promises = new Array();
  101208. if (nodes) {
  101209. promises.push(_this._loadNodesAsync(nodes));
  101210. }
  101211. else {
  101212. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  101213. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  101214. }
  101215. if (_this.compileMaterials) {
  101216. promises.push(_this._compileMaterialsAsync());
  101217. }
  101218. if (_this.compileShadowGenerators) {
  101219. promises.push(_this._compileShadowGeneratorsAsync());
  101220. }
  101221. var resultPromise = Promise.all(promises).then(function () {
  101222. _this._state = BABYLON.GLTFLoaderState.Ready;
  101223. _this._startAnimations();
  101224. });
  101225. resultPromise.then(function () {
  101226. _this._rootBabylonMesh.setEnabled(true);
  101227. BABYLON.Tools.SetImmediate(function () {
  101228. if (!_this._disposed) {
  101229. Promise.all(_this._completePromises).then(function () {
  101230. _this._state = BABYLON.GLTFLoaderState.Complete;
  101231. _this.onCompleteObservable.notifyObservers(_this);
  101232. _this.onCompleteObservable.clear();
  101233. _this._clear();
  101234. }).catch(function (error) {
  101235. BABYLON.Tools.Error("glTF Loader: " + error.message);
  101236. _this._clear();
  101237. });
  101238. }
  101239. });
  101240. });
  101241. return resultPromise;
  101242. }).catch(function (error) {
  101243. BABYLON.Tools.Error("glTF Loader: " + error.message);
  101244. _this._clear();
  101245. throw error;
  101246. });
  101247. };
  101248. GLTFLoader.prototype._loadExtensions = function () {
  101249. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  101250. var name_1 = _a[_i];
  101251. var extension = GLTFLoader._Factories[name_1](this);
  101252. this._extensions[name_1] = extension;
  101253. this.onExtensionLoadedObservable.notifyObservers(extension);
  101254. }
  101255. this.onExtensionLoadedObservable.clear();
  101256. };
  101257. GLTFLoader.prototype._loadData = function (data) {
  101258. this._gltf = data.json;
  101259. this._setupData();
  101260. if (data.bin) {
  101261. var buffers = this._gltf.buffers;
  101262. if (buffers && buffers[0] && !buffers[0].uri) {
  101263. var binaryBuffer = buffers[0];
  101264. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  101265. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  101266. }
  101267. binaryBuffer._data = Promise.resolve(data.bin);
  101268. }
  101269. else {
  101270. BABYLON.Tools.Warn("Unexpected BIN chunk");
  101271. }
  101272. }
  101273. };
  101274. GLTFLoader.prototype._setupData = function () {
  101275. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  101276. GLTF2.ArrayItem.Assign(this._gltf.animations);
  101277. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  101278. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  101279. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  101280. GLTF2.ArrayItem.Assign(this._gltf.images);
  101281. GLTF2.ArrayItem.Assign(this._gltf.materials);
  101282. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  101283. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  101284. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  101285. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  101286. GLTF2.ArrayItem.Assign(this._gltf.skins);
  101287. GLTF2.ArrayItem.Assign(this._gltf.textures);
  101288. if (this._gltf.nodes) {
  101289. var nodeParents = {};
  101290. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  101291. var node = _a[_i];
  101292. if (node.children) {
  101293. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  101294. var index = _c[_b];
  101295. nodeParents[index] = node._index;
  101296. }
  101297. }
  101298. }
  101299. var rootNode = this._createRootNode();
  101300. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  101301. var node = _e[_d];
  101302. var parentIndex = nodeParents[node._index];
  101303. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  101304. }
  101305. }
  101306. };
  101307. GLTFLoader.prototype._checkExtensions = function () {
  101308. if (this._gltf.extensionsRequired) {
  101309. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  101310. var name_2 = _a[_i];
  101311. var extension = this._extensions[name_2];
  101312. if (!extension || !extension.enabled) {
  101313. throw new Error("Require extension " + name_2 + " is not available");
  101314. }
  101315. }
  101316. }
  101317. };
  101318. GLTFLoader.prototype._createRootNode = function () {
  101319. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  101320. this._rootBabylonMesh.setEnabled(false);
  101321. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  101322. switch (this.coordinateSystemMode) {
  101323. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  101324. if (!this._babylonScene.useRightHandedSystem) {
  101325. rootNode.rotation = [0, 1, 0, 0];
  101326. rootNode.scale = [1, 1, -1];
  101327. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  101328. }
  101329. break;
  101330. }
  101331. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  101332. this._babylonScene.useRightHandedSystem = true;
  101333. break;
  101334. }
  101335. default: {
  101336. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  101337. }
  101338. }
  101339. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  101340. return rootNode;
  101341. };
  101342. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  101343. var promises = new Array();
  101344. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  101345. var node = nodes_1[_i];
  101346. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  101347. }
  101348. promises.push(this._loadAnimationsAsync());
  101349. return Promise.all(promises).then(function () { });
  101350. };
  101351. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  101352. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  101353. if (promise) {
  101354. return promise;
  101355. }
  101356. var promises = new Array();
  101357. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  101358. var index = _a[_i];
  101359. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  101360. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  101361. }
  101362. promises.push(this._loadAnimationsAsync());
  101363. return Promise.all(promises).then(function () { });
  101364. };
  101365. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  101366. if (node._primitiveBabylonMeshes) {
  101367. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  101368. var babylonMesh = _a[_i];
  101369. callback(babylonMesh);
  101370. }
  101371. }
  101372. else {
  101373. callback(node._babylonMesh);
  101374. }
  101375. };
  101376. GLTFLoader.prototype._getMeshes = function () {
  101377. var meshes = new Array();
  101378. // Root mesh is always first.
  101379. meshes.push(this._rootBabylonMesh);
  101380. var nodes = this._gltf.nodes;
  101381. if (nodes) {
  101382. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  101383. var node = nodes_2[_i];
  101384. if (node._babylonMesh) {
  101385. meshes.push(node._babylonMesh);
  101386. }
  101387. if (node._primitiveBabylonMeshes) {
  101388. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  101389. var babylonMesh = _b[_a];
  101390. meshes.push(babylonMesh);
  101391. }
  101392. }
  101393. }
  101394. }
  101395. return meshes;
  101396. };
  101397. GLTFLoader.prototype._getSkeletons = function () {
  101398. var skeletons = new Array();
  101399. var skins = this._gltf.skins;
  101400. if (skins) {
  101401. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  101402. var skin = skins_1[_i];
  101403. if (skin._babylonSkeleton) {
  101404. skeletons.push(skin._babylonSkeleton);
  101405. }
  101406. }
  101407. }
  101408. return skeletons;
  101409. };
  101410. GLTFLoader.prototype._getAnimationGroups = function () {
  101411. var animationGroups = new Array();
  101412. var animations = this._gltf.animations;
  101413. if (animations) {
  101414. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  101415. var animation = animations_1[_i];
  101416. if (animation._babylonAnimationGroup) {
  101417. animationGroups.push(animation._babylonAnimationGroup);
  101418. }
  101419. }
  101420. }
  101421. return animationGroups;
  101422. };
  101423. GLTFLoader.prototype._startAnimations = function () {
  101424. switch (this.animationStartMode) {
  101425. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  101426. // do nothing
  101427. break;
  101428. }
  101429. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  101430. var babylonAnimationGroups = this._getAnimationGroups();
  101431. if (babylonAnimationGroups.length !== 0) {
  101432. babylonAnimationGroups[0].start(true);
  101433. }
  101434. break;
  101435. }
  101436. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  101437. var babylonAnimationGroups = this._getAnimationGroups();
  101438. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  101439. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  101440. babylonAnimationGroup.start(true);
  101441. }
  101442. break;
  101443. }
  101444. default: {
  101445. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  101446. return;
  101447. }
  101448. }
  101449. };
  101450. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  101451. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  101452. if (promise) {
  101453. return promise;
  101454. }
  101455. if (node._babylonMesh) {
  101456. throw new Error(context + ": Invalid recursive node hierarchy");
  101457. }
  101458. var promises = new Array();
  101459. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  101460. node._babylonMesh = babylonMesh;
  101461. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  101462. node._babylonAnimationTargets.push(babylonMesh);
  101463. GLTFLoader._LoadTransform(node, babylonMesh);
  101464. if (node.mesh != undefined) {
  101465. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  101466. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  101467. }
  101468. if (node.children) {
  101469. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  101470. var index = _a[_i];
  101471. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  101472. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  101473. }
  101474. }
  101475. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  101476. return Promise.all(promises).then(function () { });
  101477. };
  101478. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  101479. // TODO: instancing
  101480. var _this = this;
  101481. var promises = new Array();
  101482. var primitives = mesh.primitives;
  101483. if (!primitives || primitives.length === 0) {
  101484. throw new Error(context + ": Primitives are missing");
  101485. }
  101486. GLTF2.ArrayItem.Assign(primitives);
  101487. if (primitives.length === 1) {
  101488. var primitive = primitives[0];
  101489. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  101490. }
  101491. else {
  101492. node._primitiveBabylonMeshes = [];
  101493. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  101494. var primitive = primitives_1[_i];
  101495. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  101496. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  101497. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  101498. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  101499. }
  101500. }
  101501. if (node.skin != undefined) {
  101502. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  101503. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  101504. }
  101505. return Promise.all(promises).then(function () {
  101506. _this._forEachPrimitive(node, function (babylonMesh) {
  101507. babylonMesh._refreshBoundingInfo(true);
  101508. });
  101509. });
  101510. };
  101511. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  101512. var _this = this;
  101513. var promises = new Array();
  101514. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  101515. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  101516. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  101517. babylonGeometry.applyToMesh(babylonMesh);
  101518. });
  101519. }));
  101520. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  101521. if (primitive.material == undefined) {
  101522. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  101523. }
  101524. else {
  101525. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  101526. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  101527. babylonMesh.material = babylonMaterial;
  101528. }));
  101529. }
  101530. return Promise.all(promises).then(function () { });
  101531. };
  101532. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  101533. var _this = this;
  101534. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  101535. if (promise) {
  101536. return promise;
  101537. }
  101538. var attributes = primitive.attributes;
  101539. if (!attributes) {
  101540. throw new Error(context + ": Attributes are missing");
  101541. }
  101542. var promises = new Array();
  101543. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  101544. if (primitive.indices == undefined) {
  101545. babylonMesh.isUnIndexed = true;
  101546. }
  101547. else {
  101548. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  101549. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  101550. babylonGeometry.setIndices(data);
  101551. }));
  101552. }
  101553. var loadAttribute = function (attribute, kind, callback) {
  101554. if (attributes[attribute] == undefined) {
  101555. return;
  101556. }
  101557. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  101558. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  101559. babylonMesh._delayInfo.push(kind);
  101560. }
  101561. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  101562. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  101563. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  101564. }));
  101565. if (callback) {
  101566. callback(accessor);
  101567. }
  101568. };
  101569. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  101570. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  101571. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  101572. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  101573. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  101574. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  101575. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  101576. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  101577. if (accessor.type === "VEC4" /* VEC4 */) {
  101578. babylonMesh.hasVertexAlpha = true;
  101579. }
  101580. });
  101581. return Promise.all(promises).then(function () {
  101582. return babylonGeometry;
  101583. });
  101584. };
  101585. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  101586. if (!primitive.targets) {
  101587. return;
  101588. }
  101589. if (node._numMorphTargets == undefined) {
  101590. node._numMorphTargets = primitive.targets.length;
  101591. }
  101592. else if (primitive.targets.length !== node._numMorphTargets) {
  101593. throw new Error(context + ": Primitives do not have the same number of targets");
  101594. }
  101595. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  101596. for (var index = 0; index < primitive.targets.length; index++) {
  101597. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  101598. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  101599. // TODO: tell the target whether it has positions, normals, tangents
  101600. }
  101601. };
  101602. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  101603. if (!primitive.targets) {
  101604. return Promise.resolve();
  101605. }
  101606. var promises = new Array();
  101607. var morphTargetManager = babylonMesh.morphTargetManager;
  101608. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  101609. var babylonMorphTarget = morphTargetManager.getTarget(index);
  101610. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  101611. }
  101612. return Promise.all(promises).then(function () { });
  101613. };
  101614. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  101615. var _this = this;
  101616. var promises = new Array();
  101617. var loadAttribute = function (attribute, kind, setData) {
  101618. if (attributes[attribute] == undefined) {
  101619. return;
  101620. }
  101621. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  101622. if (!babylonVertexBuffer) {
  101623. return;
  101624. }
  101625. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  101626. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  101627. if (!(data instanceof Float32Array)) {
  101628. throw new Error(context + ": Morph target accessor must have float data");
  101629. }
  101630. setData(babylonVertexBuffer, data);
  101631. }));
  101632. };
  101633. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  101634. babylonVertexBuffer.forEach(data.length, function (value, index) {
  101635. data[index] += value;
  101636. });
  101637. babylonMorphTarget.setPositions(data);
  101638. });
  101639. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  101640. babylonVertexBuffer.forEach(data.length, function (value, index) {
  101641. data[index] += value;
  101642. });
  101643. babylonMorphTarget.setNormals(data);
  101644. });
  101645. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  101646. var dataIndex = 0;
  101647. babylonVertexBuffer.forEach(data.length, function (value, index) {
  101648. // Tangent data for morph targets is stored as xyz delta.
  101649. // The vertexData.tangent is stored as xyzw.
  101650. // So we need to skip every fourth vertexData.tangent.
  101651. if (((index + 1) % 4) !== 0) {
  101652. data[dataIndex++] += value;
  101653. }
  101654. });
  101655. babylonMorphTarget.setTangents(data);
  101656. });
  101657. return Promise.all(promises).then(function () { });
  101658. };
  101659. GLTFLoader._LoadTransform = function (node, babylonNode) {
  101660. var position = BABYLON.Vector3.Zero();
  101661. var rotation = BABYLON.Quaternion.Identity();
  101662. var scaling = BABYLON.Vector3.One();
  101663. if (node.matrix) {
  101664. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  101665. matrix.decompose(scaling, rotation, position);
  101666. }
  101667. else {
  101668. if (node.translation)
  101669. position = BABYLON.Vector3.FromArray(node.translation);
  101670. if (node.rotation)
  101671. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  101672. if (node.scale)
  101673. scaling = BABYLON.Vector3.FromArray(node.scale);
  101674. }
  101675. babylonNode.position = position;
  101676. babylonNode.rotationQuaternion = rotation;
  101677. babylonNode.scaling = scaling;
  101678. };
  101679. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  101680. var _this = this;
  101681. var assignSkeleton = function () {
  101682. _this._forEachPrimitive(node, function (babylonMesh) {
  101683. babylonMesh.skeleton = skin._babylonSkeleton;
  101684. });
  101685. // Ignore the TRS of skinned nodes.
  101686. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  101687. node._babylonMesh.parent = _this._rootBabylonMesh;
  101688. node._babylonMesh.position = BABYLON.Vector3.Zero();
  101689. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  101690. node._babylonMesh.scaling = BABYLON.Vector3.One();
  101691. };
  101692. if (skin._loaded) {
  101693. return skin._loaded.then(function () {
  101694. assignSkeleton();
  101695. });
  101696. }
  101697. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  101698. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  101699. var skeletonId = "skeleton" + skin._index;
  101700. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  101701. skin._babylonSkeleton = babylonSkeleton;
  101702. _this._loadBones(context, skin, inverseBindMatricesData);
  101703. assignSkeleton();
  101704. }));
  101705. };
  101706. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  101707. if (skin.inverseBindMatrices == undefined) {
  101708. return Promise.resolve(null);
  101709. }
  101710. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  101711. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  101712. return data;
  101713. });
  101714. };
  101715. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  101716. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  101717. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  101718. node._babylonAnimationTargets.push(babylonBone);
  101719. return babylonBone;
  101720. };
  101721. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  101722. var babylonBones = {};
  101723. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  101724. var index = _a[_i];
  101725. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  101726. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  101727. }
  101728. };
  101729. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  101730. var babylonBone = babylonBones[node._index];
  101731. if (babylonBone) {
  101732. return babylonBone;
  101733. }
  101734. var boneIndex = skin.joints.indexOf(node._index);
  101735. var baseMatrix = BABYLON.Matrix.Identity();
  101736. if (inverseBindMatricesData && boneIndex !== -1) {
  101737. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  101738. baseMatrix.invertToRef(baseMatrix);
  101739. }
  101740. var babylonParentBone = null;
  101741. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  101742. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  101743. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  101744. }
  101745. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  101746. babylonBones[node._index] = babylonBone;
  101747. return babylonBone;
  101748. };
  101749. GLTFLoader.prototype._getNodeMatrix = function (node) {
  101750. return node.matrix ?
  101751. BABYLON.Matrix.FromArray(node.matrix) :
  101752. 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());
  101753. };
  101754. GLTFLoader.prototype._loadAnimationsAsync = function () {
  101755. var animations = this._gltf.animations;
  101756. if (!animations) {
  101757. return Promise.resolve();
  101758. }
  101759. var promises = new Array();
  101760. for (var index = 0; index < animations.length; index++) {
  101761. var animation = animations[index];
  101762. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  101763. }
  101764. return Promise.all(promises).then(function () { });
  101765. };
  101766. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  101767. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  101768. animation._babylonAnimationGroup = babylonAnimationGroup;
  101769. var promises = new Array();
  101770. GLTF2.ArrayItem.Assign(animation.channels);
  101771. GLTF2.ArrayItem.Assign(animation.samplers);
  101772. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  101773. var channel = _a[_i];
  101774. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  101775. }
  101776. return Promise.all(promises).then(function () {
  101777. babylonAnimationGroup.normalize();
  101778. });
  101779. };
  101780. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  101781. var _this = this;
  101782. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  101783. if (!targetNode._babylonMesh) {
  101784. return Promise.resolve();
  101785. }
  101786. // Ignore animations targeting TRS of skinned nodes.
  101787. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  101788. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  101789. return Promise.resolve();
  101790. }
  101791. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  101792. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  101793. var targetPath;
  101794. var animationType;
  101795. switch (channel.target.path) {
  101796. case "translation" /* TRANSLATION */: {
  101797. targetPath = "position";
  101798. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101799. break;
  101800. }
  101801. case "rotation" /* ROTATION */: {
  101802. targetPath = "rotationQuaternion";
  101803. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  101804. break;
  101805. }
  101806. case "scale" /* SCALE */: {
  101807. targetPath = "scaling";
  101808. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101809. break;
  101810. }
  101811. case "weights" /* WEIGHTS */: {
  101812. targetPath = "influence";
  101813. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  101814. break;
  101815. }
  101816. default: {
  101817. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  101818. }
  101819. }
  101820. var outputBufferOffset = 0;
  101821. var getNextOutputValue;
  101822. switch (targetPath) {
  101823. case "position": {
  101824. getNextOutputValue = function () {
  101825. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  101826. outputBufferOffset += 3;
  101827. return value;
  101828. };
  101829. break;
  101830. }
  101831. case "rotationQuaternion": {
  101832. getNextOutputValue = function () {
  101833. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  101834. outputBufferOffset += 4;
  101835. return value;
  101836. };
  101837. break;
  101838. }
  101839. case "scaling": {
  101840. getNextOutputValue = function () {
  101841. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  101842. outputBufferOffset += 3;
  101843. return value;
  101844. };
  101845. break;
  101846. }
  101847. case "influence": {
  101848. getNextOutputValue = function () {
  101849. var value = new Array(targetNode._numMorphTargets);
  101850. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  101851. value[i] = data.output[outputBufferOffset++];
  101852. }
  101853. return value;
  101854. };
  101855. break;
  101856. }
  101857. }
  101858. var getNextKey;
  101859. switch (data.interpolation) {
  101860. case "STEP" /* STEP */: {
  101861. getNextKey = function (frameIndex) { return ({
  101862. frame: data.input[frameIndex],
  101863. value: getNextOutputValue(),
  101864. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  101865. }); };
  101866. break;
  101867. }
  101868. case "LINEAR" /* LINEAR */: {
  101869. getNextKey = function (frameIndex) { return ({
  101870. frame: data.input[frameIndex],
  101871. value: getNextOutputValue()
  101872. }); };
  101873. break;
  101874. }
  101875. case "CUBICSPLINE" /* CUBICSPLINE */: {
  101876. getNextKey = function (frameIndex) { return ({
  101877. frame: data.input[frameIndex],
  101878. inTangent: getNextOutputValue(),
  101879. value: getNextOutputValue(),
  101880. outTangent: getNextOutputValue()
  101881. }); };
  101882. break;
  101883. }
  101884. }
  101885. var keys = new Array(data.input.length);
  101886. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  101887. keys[frameIndex] = getNextKey(frameIndex);
  101888. }
  101889. if (targetPath === "influence") {
  101890. var _loop_1 = function (targetIndex) {
  101891. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  101892. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  101893. babylonAnimation.setKeys(keys.map(function (key) { return ({
  101894. frame: key.frame,
  101895. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  101896. value: key.value[targetIndex],
  101897. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  101898. }); }));
  101899. var multiTarget = new GLTF2.AnimationMultiTarget();
  101900. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  101901. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  101902. multiTarget.subTargets.push(morphTarget);
  101903. });
  101904. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, multiTarget);
  101905. };
  101906. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  101907. _loop_1(targetIndex);
  101908. }
  101909. }
  101910. else {
  101911. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  101912. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  101913. babylonAnimation.setKeys(keys);
  101914. if (targetNode._babylonAnimationTargets) {
  101915. var multiTarget = new GLTF2.AnimationMultiTarget();
  101916. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  101917. var target = _a[_i];
  101918. multiTarget.subTargets.push(target);
  101919. }
  101920. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, multiTarget);
  101921. }
  101922. }
  101923. });
  101924. };
  101925. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  101926. if (sampler._data) {
  101927. return sampler._data;
  101928. }
  101929. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  101930. switch (interpolation) {
  101931. case "STEP" /* STEP */:
  101932. case "LINEAR" /* LINEAR */:
  101933. case "CUBICSPLINE" /* CUBICSPLINE */: {
  101934. break;
  101935. }
  101936. default: {
  101937. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  101938. }
  101939. }
  101940. var inputData;
  101941. var outputData;
  101942. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  101943. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  101944. sampler._data = Promise.all([
  101945. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  101946. inputData = data;
  101947. }),
  101948. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  101949. outputData = data;
  101950. })
  101951. ]).then(function () {
  101952. return {
  101953. input: inputData,
  101954. interpolation: interpolation,
  101955. output: outputData,
  101956. };
  101957. });
  101958. return sampler._data;
  101959. };
  101960. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  101961. if (buffer._data) {
  101962. return buffer._data;
  101963. }
  101964. if (!buffer.uri) {
  101965. throw new Error(context + ": Uri is missing");
  101966. }
  101967. buffer._data = this._loadUriAsync(context, buffer.uri);
  101968. return buffer._data;
  101969. };
  101970. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  101971. if (bufferView._data) {
  101972. return bufferView._data;
  101973. }
  101974. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  101975. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  101976. try {
  101977. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  101978. }
  101979. catch (e) {
  101980. throw new Error(context + ": " + e.message);
  101981. }
  101982. });
  101983. return bufferView._data;
  101984. };
  101985. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  101986. if (accessor.sparse) {
  101987. throw new Error(context + ": Sparse accessors are not currently supported");
  101988. }
  101989. if (accessor._data) {
  101990. return accessor._data;
  101991. }
  101992. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  101993. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  101994. var buffer = data.buffer;
  101995. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  101996. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  101997. try {
  101998. switch (accessor.componentType) {
  101999. case 5120 /* BYTE */: {
  102000. return new Int8Array(buffer, byteOffset, length);
  102001. }
  102002. case 5121 /* UNSIGNED_BYTE */: {
  102003. return new Uint8Array(buffer, byteOffset, length);
  102004. }
  102005. case 5122 /* SHORT */: {
  102006. return new Int16Array(buffer, byteOffset, length);
  102007. }
  102008. case 5123 /* UNSIGNED_SHORT */: {
  102009. return new Uint16Array(buffer, byteOffset, length);
  102010. }
  102011. case 5125 /* UNSIGNED_INT */: {
  102012. return new Uint32Array(buffer, byteOffset, length);
  102013. }
  102014. case 5126 /* FLOAT */: {
  102015. return new Float32Array(buffer, byteOffset, length);
  102016. }
  102017. default: {
  102018. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  102019. }
  102020. }
  102021. }
  102022. catch (e) {
  102023. throw new Error(context + ": " + e);
  102024. }
  102025. });
  102026. return accessor._data;
  102027. };
  102028. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  102029. var _this = this;
  102030. if (bufferView._babylonBuffer) {
  102031. return bufferView._babylonBuffer;
  102032. }
  102033. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  102034. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  102035. });
  102036. return bufferView._babylonBuffer;
  102037. };
  102038. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  102039. var _this = this;
  102040. if (accessor.sparse) {
  102041. throw new Error(context + ": Sparse accessors are not currently supported");
  102042. }
  102043. if (accessor._babylonVertexBuffer) {
  102044. return accessor._babylonVertexBuffer;
  102045. }
  102046. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  102047. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  102048. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  102049. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  102050. });
  102051. return accessor._babylonVertexBuffer;
  102052. };
  102053. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  102054. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  102055. if (!babylonMaterial) {
  102056. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  102057. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  102058. babylonMaterial.metallic = 1;
  102059. babylonMaterial.roughness = 1;
  102060. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  102061. }
  102062. return babylonMaterial;
  102063. };
  102064. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  102065. var promises = new Array();
  102066. // Ensure metallic workflow
  102067. babylonMaterial.metallic = 1;
  102068. babylonMaterial.roughness = 1;
  102069. var properties = material.pbrMetallicRoughness;
  102070. if (properties) {
  102071. if (properties.baseColorFactor) {
  102072. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  102073. babylonMaterial.alpha = properties.baseColorFactor[3];
  102074. }
  102075. else {
  102076. babylonMaterial.albedoColor = BABYLON.Color3.White();
  102077. }
  102078. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  102079. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  102080. if (properties.baseColorTexture) {
  102081. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  102082. babylonMaterial.albedoTexture = texture;
  102083. }));
  102084. }
  102085. if (properties.metallicRoughnessTexture) {
  102086. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  102087. babylonMaterial.metallicTexture = texture;
  102088. }));
  102089. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  102090. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  102091. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  102092. }
  102093. }
  102094. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  102095. return Promise.all(promises).then(function () { });
  102096. };
  102097. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  102098. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  102099. if (promise) {
  102100. return promise;
  102101. }
  102102. material._babylonData = material._babylonData || {};
  102103. var babylonData = material._babylonData[babylonDrawMode];
  102104. if (!babylonData) {
  102105. var promises = new Array();
  102106. var name_3 = material.name || "materialSG_" + material._index;
  102107. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  102108. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  102109. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  102110. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  102111. babylonData = {
  102112. material: babylonMaterial,
  102113. meshes: [],
  102114. loaded: Promise.all(promises).then(function () { })
  102115. };
  102116. material._babylonData[babylonDrawMode] = babylonData;
  102117. }
  102118. babylonData.meshes.push(babylonMesh);
  102119. assign(babylonData.material);
  102120. return babylonData.loaded;
  102121. };
  102122. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  102123. var babylonMaterial = new type(name, this._babylonScene);
  102124. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  102125. babylonMaterial.fillMode = drawMode;
  102126. return babylonMaterial;
  102127. };
  102128. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  102129. var promises = new Array();
  102130. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  102131. if (material.doubleSided) {
  102132. babylonMaterial.backFaceCulling = false;
  102133. babylonMaterial.twoSidedLighting = true;
  102134. }
  102135. if (material.normalTexture) {
  102136. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  102137. babylonMaterial.bumpTexture = texture;
  102138. }));
  102139. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  102140. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  102141. if (material.normalTexture.scale != undefined) {
  102142. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  102143. }
  102144. }
  102145. if (material.occlusionTexture) {
  102146. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  102147. babylonMaterial.ambientTexture = texture;
  102148. }));
  102149. babylonMaterial.useAmbientInGrayScale = true;
  102150. if (material.occlusionTexture.strength != undefined) {
  102151. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  102152. }
  102153. }
  102154. if (material.emissiveTexture) {
  102155. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  102156. babylonMaterial.emissiveTexture = texture;
  102157. }));
  102158. }
  102159. return Promise.all(promises).then(function () { });
  102160. };
  102161. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  102162. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  102163. switch (alphaMode) {
  102164. case "OPAQUE" /* OPAQUE */: {
  102165. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  102166. break;
  102167. }
  102168. case "MASK" /* MASK */: {
  102169. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  102170. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  102171. if (babylonMaterial.albedoTexture) {
  102172. babylonMaterial.albedoTexture.hasAlpha = true;
  102173. }
  102174. break;
  102175. }
  102176. case "BLEND" /* BLEND */: {
  102177. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  102178. if (babylonMaterial.albedoTexture) {
  102179. babylonMaterial.albedoTexture.hasAlpha = true;
  102180. babylonMaterial.useAlphaFromAlbedoTexture = true;
  102181. }
  102182. break;
  102183. }
  102184. default: {
  102185. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  102186. }
  102187. }
  102188. };
  102189. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  102190. var _this = this;
  102191. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  102192. context = "#/textures/" + textureInfo.index;
  102193. var promises = new Array();
  102194. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  102195. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  102196. var deferred = new BABYLON.Deferred();
  102197. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  102198. if (!_this._disposed) {
  102199. deferred.resolve();
  102200. }
  102201. }, function (message, exception) {
  102202. if (!_this._disposed) {
  102203. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  102204. }
  102205. });
  102206. promises.push(deferred.promise);
  102207. babylonTexture.name = texture.name || "texture" + texture._index;
  102208. babylonTexture.wrapU = samplerData.wrapU;
  102209. babylonTexture.wrapV = samplerData.wrapV;
  102210. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  102211. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  102212. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  102213. babylonTexture.updateURL(objectURL);
  102214. }));
  102215. assign(babylonTexture);
  102216. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  102217. return Promise.all(promises).then(function () { });
  102218. };
  102219. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  102220. if (!sampler._data) {
  102221. sampler._data = {
  102222. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  102223. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  102224. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  102225. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  102226. };
  102227. }
  102228. ;
  102229. return sampler._data;
  102230. };
  102231. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  102232. if (image._objectURL) {
  102233. return image._objectURL;
  102234. }
  102235. var promise;
  102236. if (image.uri) {
  102237. promise = this._loadUriAsync(context, image.uri);
  102238. }
  102239. else {
  102240. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  102241. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  102242. }
  102243. image._objectURL = promise.then(function (data) {
  102244. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  102245. });
  102246. return image._objectURL;
  102247. };
  102248. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  102249. var _this = this;
  102250. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  102251. if (promise) {
  102252. return promise;
  102253. }
  102254. if (!GLTFLoader._ValidateUri(uri)) {
  102255. throw new Error(context + ": Uri '" + uri + "' is invalid");
  102256. }
  102257. if (BABYLON.Tools.IsBase64(uri)) {
  102258. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  102259. }
  102260. return new Promise(function (resolve, reject) {
  102261. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  102262. if (!_this._disposed) {
  102263. resolve(new Uint8Array(data));
  102264. }
  102265. }, function (event) {
  102266. if (!_this._disposed) {
  102267. try {
  102268. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  102269. request._lengthComputable = event.lengthComputable;
  102270. request._loaded = event.loaded;
  102271. request._total = event.total;
  102272. _this._onProgress();
  102273. }
  102274. }
  102275. catch (e) {
  102276. reject(e);
  102277. }
  102278. }
  102279. }, _this._babylonScene.database, true, function (request, exception) {
  102280. if (!_this._disposed) {
  102281. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  102282. }
  102283. });
  102284. _this._requests.push(request);
  102285. });
  102286. };
  102287. GLTFLoader.prototype._onProgress = function () {
  102288. if (!this._progressCallback) {
  102289. return;
  102290. }
  102291. var lengthComputable = true;
  102292. var loaded = 0;
  102293. var total = 0;
  102294. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  102295. var request = _a[_i];
  102296. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  102297. return;
  102298. }
  102299. lengthComputable = lengthComputable && request._lengthComputable;
  102300. loaded += request._loaded;
  102301. total += request._total;
  102302. }
  102303. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  102304. };
  102305. GLTFLoader._GetProperty = function (context, array, index) {
  102306. if (!array || index == undefined || !array[index]) {
  102307. throw new Error(context + ": Failed to find index (" + index + ")");
  102308. }
  102309. return array[index];
  102310. };
  102311. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  102312. // Set defaults if undefined
  102313. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  102314. switch (mode) {
  102315. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  102316. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  102317. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102318. default:
  102319. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  102320. return BABYLON.Texture.WRAP_ADDRESSMODE;
  102321. }
  102322. };
  102323. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  102324. // Set defaults if undefined
  102325. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  102326. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  102327. if (magFilter === 9729 /* LINEAR */) {
  102328. switch (minFilter) {
  102329. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  102330. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  102331. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  102332. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  102333. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  102334. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  102335. default:
  102336. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  102337. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  102338. }
  102339. }
  102340. else {
  102341. if (magFilter !== 9728 /* NEAREST */) {
  102342. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  102343. }
  102344. switch (minFilter) {
  102345. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  102346. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  102347. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  102348. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  102349. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  102350. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  102351. default:
  102352. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  102353. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  102354. }
  102355. }
  102356. };
  102357. GLTFLoader._GetNumComponents = function (context, type) {
  102358. switch (type) {
  102359. case "SCALAR": return 1;
  102360. case "VEC2": return 2;
  102361. case "VEC3": return 3;
  102362. case "VEC4": return 4;
  102363. case "MAT2": return 4;
  102364. case "MAT3": return 9;
  102365. case "MAT4": return 16;
  102366. }
  102367. throw new Error(context + ": Invalid type (" + type + ")");
  102368. };
  102369. GLTFLoader._ValidateUri = function (uri) {
  102370. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  102371. };
  102372. GLTFLoader._GetDrawMode = function (context, mode) {
  102373. if (mode == undefined) {
  102374. mode = 4 /* TRIANGLES */;
  102375. }
  102376. switch (mode) {
  102377. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  102378. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  102379. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  102380. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  102381. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  102382. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  102383. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  102384. }
  102385. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  102386. };
  102387. GLTFLoader.prototype._compileMaterialsAsync = function () {
  102388. var promises = new Array();
  102389. if (this._gltf.materials) {
  102390. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  102391. var material = _a[_i];
  102392. if (material._babylonData) {
  102393. for (var babylonDrawMode in material._babylonData) {
  102394. var babylonData = material._babylonData[babylonDrawMode];
  102395. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  102396. var babylonMesh = _c[_b];
  102397. // Ensure nonUniformScaling is set if necessary.
  102398. babylonMesh.computeWorldMatrix(true);
  102399. var babylonMaterial = babylonData.material;
  102400. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  102401. if (this.useClipPlane) {
  102402. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  102403. }
  102404. }
  102405. }
  102406. }
  102407. }
  102408. }
  102409. return Promise.all(promises).then(function () { });
  102410. };
  102411. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  102412. var promises = new Array();
  102413. var lights = this._babylonScene.lights;
  102414. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  102415. var light = lights_1[_i];
  102416. var generator = light.getShadowGenerator();
  102417. if (generator) {
  102418. promises.push(generator.forceCompilationAsync());
  102419. }
  102420. }
  102421. return Promise.all(promises).then(function () { });
  102422. };
  102423. GLTFLoader.prototype._clear = function () {
  102424. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  102425. var request = _a[_i];
  102426. request.abort();
  102427. }
  102428. this._requests.length = 0;
  102429. if (this._gltf && this._gltf.images) {
  102430. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  102431. var image = _c[_b];
  102432. if (image._objectURL) {
  102433. image._objectURL.then(function (value) {
  102434. URL.revokeObjectURL(value);
  102435. });
  102436. image._objectURL = undefined;
  102437. }
  102438. }
  102439. }
  102440. delete this._gltf;
  102441. delete this._babylonScene;
  102442. this._completePromises.length = 0;
  102443. for (var name_4 in this._extensions) {
  102444. this._extensions[name_4].dispose();
  102445. }
  102446. this._extensions = {};
  102447. delete this._rootBabylonMesh;
  102448. delete this._progressCallback;
  102449. this.onMeshLoadedObservable.clear();
  102450. this.onTextureLoadedObservable.clear();
  102451. this.onMaterialLoadedObservable.clear();
  102452. };
  102453. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  102454. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  102455. var name_5 = _a[_i];
  102456. var extension = this._extensions[name_5];
  102457. if (extension.enabled) {
  102458. var promise = actionAsync(extension);
  102459. if (promise) {
  102460. return promise;
  102461. }
  102462. }
  102463. }
  102464. return null;
  102465. };
  102466. GLTFLoader._Names = new Array();
  102467. GLTFLoader._Factories = {};
  102468. return GLTFLoader;
  102469. }());
  102470. GLTF2.GLTFLoader = GLTFLoader;
  102471. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  102472. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102473. })(BABYLON || (BABYLON = {}));
  102474. //# sourceMappingURL=babylon.glTFLoader.js.map
  102475. "use strict";
  102476. var BABYLON;
  102477. (function (BABYLON) {
  102478. var GLTF2;
  102479. (function (GLTF2) {
  102480. var GLTFLoaderExtension = /** @class */ (function () {
  102481. function GLTFLoaderExtension(loader) {
  102482. this.enabled = true;
  102483. this._loader = loader;
  102484. }
  102485. GLTFLoaderExtension.prototype.dispose = function () {
  102486. delete this._loader;
  102487. };
  102488. // #region Overridable Methods
  102489. /** Override this method to modify the default behavior for loading scenes. */
  102490. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  102491. /** Override this method to modify the default behavior for loading nodes. */
  102492. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  102493. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  102494. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  102495. /** Override this method to modify the default behavior for loading materials. */
  102496. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  102497. /** Override this method to modify the default behavior for loading uris. */
  102498. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  102499. // #endregion
  102500. /** Helper method called by a loader extension to load an glTF extension. */
  102501. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  102502. if (!property.extensions) {
  102503. return null;
  102504. }
  102505. var extensions = property.extensions;
  102506. var extension = extensions[this.name];
  102507. if (!extension) {
  102508. return null;
  102509. }
  102510. // Clear out the extension before executing the action to avoid recursing into the same property.
  102511. delete extensions[this.name];
  102512. try {
  102513. return actionAsync(context + "/extensions/" + this.name, extension);
  102514. }
  102515. finally {
  102516. // Restore the extension after executing the action.
  102517. extensions[this.name] = extension;
  102518. }
  102519. };
  102520. /** Helper method called by the loader to allow extensions to override loading scenes. */
  102521. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  102522. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  102523. };
  102524. /** Helper method called by the loader to allow extensions to override loading nodes. */
  102525. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  102526. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  102527. };
  102528. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  102529. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  102530. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  102531. };
  102532. /** Helper method called by the loader to allow extensions to override loading materials. */
  102533. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  102534. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  102535. };
  102536. /** Helper method called by the loader to allow extensions to override loading uris. */
  102537. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  102538. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  102539. };
  102540. return GLTFLoaderExtension;
  102541. }());
  102542. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  102543. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102544. })(BABYLON || (BABYLON = {}));
  102545. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  102546. "use strict";
  102547. var BABYLON;
  102548. (function (BABYLON) {
  102549. var GLTF2;
  102550. (function (GLTF2) {
  102551. var Extensions;
  102552. (function (Extensions) {
  102553. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  102554. var NAME = "MSFT_lod";
  102555. var MSFT_lod = /** @class */ (function (_super) {
  102556. __extends(MSFT_lod, _super);
  102557. function MSFT_lod() {
  102558. var _this = _super !== null && _super.apply(this, arguments) || this;
  102559. _this.name = NAME;
  102560. /**
  102561. * Maximum number of LODs to load, starting from the lowest LOD.
  102562. */
  102563. _this.maxLODsToLoad = Number.MAX_VALUE;
  102564. _this._loadingNodeLOD = null;
  102565. _this._loadNodeSignals = {};
  102566. _this._loadingMaterialLOD = null;
  102567. _this._loadMaterialSignals = {};
  102568. return _this;
  102569. }
  102570. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  102571. var _this = this;
  102572. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  102573. var firstPromise;
  102574. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  102575. var _loop_1 = function (indexLOD) {
  102576. var nodeLOD = nodeLODs[indexLOD];
  102577. if (indexLOD !== 0) {
  102578. _this._loadingNodeLOD = nodeLOD;
  102579. if (!_this._loadNodeSignals[nodeLOD._index]) {
  102580. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  102581. }
  102582. }
  102583. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  102584. if (indexLOD !== 0) {
  102585. var previousNodeLOD = nodeLODs[indexLOD - 1];
  102586. if (previousNodeLOD._babylonMesh) {
  102587. previousNodeLOD._babylonMesh.dispose(false, true);
  102588. delete previousNodeLOD._babylonMesh;
  102589. }
  102590. }
  102591. if (indexLOD !== nodeLODs.length - 1) {
  102592. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  102593. if (_this._loadNodeSignals[nodeIndex]) {
  102594. _this._loadNodeSignals[nodeIndex].resolve();
  102595. delete _this._loadNodeSignals[nodeIndex];
  102596. }
  102597. }
  102598. });
  102599. if (indexLOD === 0) {
  102600. firstPromise = promise;
  102601. }
  102602. else {
  102603. _this._loader._completePromises.push(promise);
  102604. _this._loadingNodeLOD = null;
  102605. }
  102606. };
  102607. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  102608. _loop_1(indexLOD);
  102609. }
  102610. return firstPromise;
  102611. });
  102612. };
  102613. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  102614. var _this = this;
  102615. // Don't load material LODs if already loading a node LOD.
  102616. if (this._loadingNodeLOD) {
  102617. return null;
  102618. }
  102619. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  102620. var firstPromise;
  102621. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  102622. var _loop_2 = function (indexLOD) {
  102623. var materialLOD = materialLODs[indexLOD];
  102624. if (indexLOD !== 0) {
  102625. _this._loadingMaterialLOD = materialLOD;
  102626. if (!_this._loadMaterialSignals[materialLOD._index]) {
  102627. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  102628. }
  102629. }
  102630. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  102631. if (indexLOD !== 0) {
  102632. var babylonDataLOD = materialLOD._babylonData;
  102633. assign(babylonDataLOD[babylonDrawMode].material);
  102634. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  102635. if (previousBabylonDataLOD[babylonDrawMode]) {
  102636. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  102637. delete previousBabylonDataLOD[babylonDrawMode];
  102638. }
  102639. }
  102640. if (indexLOD !== materialLODs.length - 1) {
  102641. var materialIndex = materialLODs[indexLOD + 1]._index;
  102642. if (_this._loadMaterialSignals[materialIndex]) {
  102643. _this._loadMaterialSignals[materialIndex].resolve();
  102644. delete _this._loadMaterialSignals[materialIndex];
  102645. }
  102646. }
  102647. });
  102648. if (indexLOD === 0) {
  102649. firstPromise = promise;
  102650. }
  102651. else {
  102652. _this._loader._completePromises.push(promise);
  102653. _this._loadingMaterialLOD = null;
  102654. }
  102655. };
  102656. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  102657. _loop_2(indexLOD);
  102658. }
  102659. return firstPromise;
  102660. });
  102661. };
  102662. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  102663. var _this = this;
  102664. // Defer the loading of uris if loading a material or node LOD.
  102665. if (this._loadingMaterialLOD) {
  102666. var index = this._loadingMaterialLOD._index;
  102667. return this._loadMaterialSignals[index].promise.then(function () {
  102668. return _this._loader._loadUriAsync(context, uri);
  102669. });
  102670. }
  102671. else if (this._loadingNodeLOD) {
  102672. var index = this._loadingNodeLOD._index;
  102673. return this._loadNodeSignals[index].promise.then(function () {
  102674. return _this._loader._loadUriAsync(context, uri);
  102675. });
  102676. }
  102677. return null;
  102678. };
  102679. /**
  102680. * Gets an array of LOD properties from lowest to highest.
  102681. */
  102682. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  102683. if (this.maxLODsToLoad <= 0) {
  102684. throw new Error("maxLODsToLoad must be greater than zero");
  102685. }
  102686. var properties = new Array();
  102687. for (var i = ids.length - 1; i >= 0; i--) {
  102688. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  102689. if (properties.length === this.maxLODsToLoad) {
  102690. return properties;
  102691. }
  102692. }
  102693. properties.push(property);
  102694. return properties;
  102695. };
  102696. return MSFT_lod;
  102697. }(GLTF2.GLTFLoaderExtension));
  102698. Extensions.MSFT_lod = MSFT_lod;
  102699. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  102700. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  102701. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102702. })(BABYLON || (BABYLON = {}));
  102703. //# sourceMappingURL=MSFT_lod.js.map
  102704. "use strict";
  102705. var BABYLON;
  102706. (function (BABYLON) {
  102707. var GLTF2;
  102708. (function (GLTF2) {
  102709. var Extensions;
  102710. (function (Extensions) {
  102711. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  102712. var NAME = "KHR_draco_mesh_compression";
  102713. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  102714. __extends(KHR_draco_mesh_compression, _super);
  102715. function KHR_draco_mesh_compression(loader) {
  102716. var _this = _super.call(this, loader) || this;
  102717. _this.name = NAME;
  102718. _this._dracoCompression = null;
  102719. // Disable extension if decoder is not available.
  102720. if (!BABYLON.DracoCompression.DecoderUrl) {
  102721. _this.enabled = false;
  102722. }
  102723. return _this;
  102724. }
  102725. KHR_draco_mesh_compression.prototype.dispose = function () {
  102726. if (this._dracoCompression) {
  102727. this._dracoCompression.dispose();
  102728. }
  102729. _super.prototype.dispose.call(this);
  102730. };
  102731. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  102732. var _this = this;
  102733. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  102734. if (primitive.mode != undefined) {
  102735. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  102736. primitive.mode !== 4 /* TRIANGLES */) {
  102737. throw new Error(context + ": Unsupported mode " + primitive.mode);
  102738. }
  102739. // TODO: handle triangle strips
  102740. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  102741. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  102742. }
  102743. }
  102744. var attributes = {};
  102745. var loadAttribute = function (name, kind) {
  102746. var uniqueId = extension.attributes[name];
  102747. if (uniqueId == undefined) {
  102748. return;
  102749. }
  102750. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  102751. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  102752. babylonMesh._delayInfo.push(kind);
  102753. }
  102754. attributes[kind] = uniqueId;
  102755. };
  102756. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  102757. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  102758. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  102759. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  102760. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  102761. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  102762. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  102763. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  102764. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  102765. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  102766. try {
  102767. if (!_this._dracoCompression) {
  102768. _this._dracoCompression = new BABYLON.DracoCompression();
  102769. }
  102770. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  102771. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  102772. babylonVertexData.applyToGeometry(babylonGeometry);
  102773. return babylonGeometry;
  102774. });
  102775. }
  102776. catch (e) {
  102777. throw new Error(context + ": " + e.message);
  102778. }
  102779. });
  102780. });
  102781. };
  102782. return KHR_draco_mesh_compression;
  102783. }(GLTF2.GLTFLoaderExtension));
  102784. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  102785. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  102786. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  102787. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102788. })(BABYLON || (BABYLON = {}));
  102789. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  102790. "use strict";
  102791. var BABYLON;
  102792. (function (BABYLON) {
  102793. var GLTF2;
  102794. (function (GLTF2) {
  102795. var Extensions;
  102796. (function (Extensions) {
  102797. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  102798. var NAME = "KHR_materials_pbrSpecularGlossiness";
  102799. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  102800. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  102801. function KHR_materials_pbrSpecularGlossiness() {
  102802. var _this = _super !== null && _super.apply(this, arguments) || this;
  102803. _this.name = NAME;
  102804. return _this;
  102805. }
  102806. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  102807. var _this = this;
  102808. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  102809. material._babylonData = material._babylonData || {};
  102810. var babylonData = material._babylonData[babylonDrawMode];
  102811. if (!babylonData) {
  102812. var promises = new Array();
  102813. var name_1 = material.name || "materialSG_" + material._index;
  102814. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  102815. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  102816. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  102817. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  102818. babylonData = {
  102819. material: babylonMaterial,
  102820. meshes: [],
  102821. loaded: Promise.all(promises).then(function () { })
  102822. };
  102823. material._babylonData[babylonDrawMode] = babylonData;
  102824. }
  102825. babylonData.meshes.push(babylonMesh);
  102826. assign(babylonData.material);
  102827. return babylonData.loaded;
  102828. });
  102829. };
  102830. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  102831. var promises = new Array();
  102832. if (properties.diffuseFactor) {
  102833. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  102834. babylonMaterial.alpha = properties.diffuseFactor[3];
  102835. }
  102836. else {
  102837. babylonMaterial.albedoColor = BABYLON.Color3.White();
  102838. }
  102839. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  102840. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  102841. if (properties.diffuseTexture) {
  102842. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  102843. babylonMaterial.albedoTexture = texture;
  102844. }));
  102845. }
  102846. if (properties.specularGlossinessTexture) {
  102847. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  102848. babylonMaterial.reflectivityTexture = texture;
  102849. }));
  102850. babylonMaterial.reflectivityTexture.hasAlpha = true;
  102851. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  102852. }
  102853. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  102854. return Promise.all(promises).then(function () { });
  102855. };
  102856. return KHR_materials_pbrSpecularGlossiness;
  102857. }(GLTF2.GLTFLoaderExtension));
  102858. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  102859. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  102860. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  102861. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102862. })(BABYLON || (BABYLON = {}));
  102863. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  102864. "use strict";
  102865. var BABYLON;
  102866. (function (BABYLON) {
  102867. var GLTF2;
  102868. (function (GLTF2) {
  102869. var Extensions;
  102870. (function (Extensions) {
  102871. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  102872. var NAME = "KHR_materials_unlit";
  102873. var KHR_materials_unlit = /** @class */ (function (_super) {
  102874. __extends(KHR_materials_unlit, _super);
  102875. function KHR_materials_unlit() {
  102876. var _this = _super !== null && _super.apply(this, arguments) || this;
  102877. _this.name = NAME;
  102878. return _this;
  102879. }
  102880. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  102881. var _this = this;
  102882. return this._loadExtensionAsync(context, material, function () {
  102883. material._babylonData = material._babylonData || {};
  102884. var babylonData = material._babylonData[babylonDrawMode];
  102885. if (!babylonData) {
  102886. var name_1 = material.name || "materialUnlit_" + material._index;
  102887. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  102888. babylonMaterial.unlit = true;
  102889. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  102890. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  102891. babylonData = {
  102892. material: babylonMaterial,
  102893. meshes: [],
  102894. loaded: promise
  102895. };
  102896. material._babylonData[babylonDrawMode] = babylonData;
  102897. }
  102898. babylonData.meshes.push(babylonMesh);
  102899. assign(babylonData.material);
  102900. return babylonData.loaded;
  102901. });
  102902. };
  102903. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  102904. var promises = new Array();
  102905. // Ensure metallic workflow
  102906. babylonMaterial.metallic = 1;
  102907. babylonMaterial.roughness = 1;
  102908. var properties = material.pbrMetallicRoughness;
  102909. if (properties) {
  102910. if (properties.baseColorFactor) {
  102911. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  102912. babylonMaterial.alpha = properties.baseColorFactor[3];
  102913. }
  102914. else {
  102915. babylonMaterial.albedoColor = BABYLON.Color3.White();
  102916. }
  102917. if (properties.baseColorTexture) {
  102918. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  102919. babylonMaterial.albedoTexture = texture;
  102920. }));
  102921. }
  102922. }
  102923. if (material.doubleSided) {
  102924. babylonMaterial.backFaceCulling = false;
  102925. babylonMaterial.twoSidedLighting = true;
  102926. }
  102927. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  102928. return Promise.all(promises).then(function () { });
  102929. };
  102930. return KHR_materials_unlit;
  102931. }(GLTF2.GLTFLoaderExtension));
  102932. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  102933. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  102934. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  102935. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  102936. })(BABYLON || (BABYLON = {}));
  102937. //# sourceMappingURL=KHR_materials_unlit.js.map
  102938. "use strict";
  102939. var BABYLON;
  102940. (function (BABYLON) {
  102941. var GLTF2;
  102942. (function (GLTF2) {
  102943. var Extensions;
  102944. (function (Extensions) {
  102945. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  102946. var NAME = "KHR_lights";
  102947. var LightType;
  102948. (function (LightType) {
  102949. LightType["AMBIENT"] = "ambient";
  102950. LightType["DIRECTIONAL"] = "directional";
  102951. LightType["POINT"] = "point";
  102952. LightType["SPOT"] = "spot";
  102953. })(LightType || (LightType = {}));
  102954. var KHR_lights = /** @class */ (function (_super) {
  102955. __extends(KHR_lights, _super);
  102956. function KHR_lights() {
  102957. var _this = _super !== null && _super.apply(this, arguments) || this;
  102958. _this.name = NAME;
  102959. return _this;
  102960. }
  102961. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  102962. var _this = this;
  102963. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  102964. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  102965. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  102966. if (light.type !== LightType.AMBIENT) {
  102967. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  102968. }
  102969. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  102970. return promise;
  102971. });
  102972. };
  102973. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  102974. var _this = this;
  102975. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  102976. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  102977. var babylonLight;
  102978. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  102979. var name = node._babylonMesh.name;
  102980. switch (light.type) {
  102981. case LightType.AMBIENT: {
  102982. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  102983. }
  102984. case LightType.DIRECTIONAL: {
  102985. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  102986. break;
  102987. }
  102988. case LightType.POINT: {
  102989. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  102990. break;
  102991. }
  102992. case LightType.SPOT: {
  102993. var spotLight = light;
  102994. // TODO: support inner and outer cone angles
  102995. //const innerConeAngle = spotLight.innerConeAngle || 0;
  102996. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  102997. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  102998. break;
  102999. }
  103000. default: {
  103001. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  103002. }
  103003. }
  103004. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  103005. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  103006. babylonLight.parent = node._babylonMesh;
  103007. return promise;
  103008. });
  103009. };
  103010. Object.defineProperty(KHR_lights.prototype, "_lights", {
  103011. get: function () {
  103012. var extensions = this._loader._gltf.extensions;
  103013. if (!extensions || !extensions[this.name]) {
  103014. throw new Error("#/extensions: '" + this.name + "' not found");
  103015. }
  103016. var extension = extensions[this.name];
  103017. return extension.lights;
  103018. },
  103019. enumerable: true,
  103020. configurable: true
  103021. });
  103022. return KHR_lights;
  103023. }(GLTF2.GLTFLoaderExtension));
  103024. Extensions.KHR_lights = KHR_lights;
  103025. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  103026. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  103027. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  103028. })(BABYLON || (BABYLON = {}));
  103029. //# sourceMappingURL=KHR_lights.js.map
  103030. return BABYLON;
  103031. });
  103032. /***/ }),
  103033. /* 35 */
  103034. /***/ (function(module, exports, __webpack_require__) {
  103035. /*!
  103036. * PEP v0.4.3 | https://github.com/jquery/PEP
  103037. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  103038. */
  103039. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  103040. // define inherited MouseEvent properties
  103041. // skip bubbles and cancelable since they're set above in initEvent()
  103042. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  103043. // Spec requires that pointers without pressure specified use 0.5 for down
  103044. // state and 0 for up state.
  103045. var f=0;
  103046. // add x/y properties aliased to clientX/Y
  103047. // define the properties of the PointerEvent interface
  103048. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  103049. // only activate if this platform does not have pointer events
  103050. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  103051. * This is the constructor for new PointerEvents.
  103052. *
  103053. * New Pointer Events must be given a type, and an optional dictionary of
  103054. * initialization properties.
  103055. *
  103056. * Due to certain platform requirements, events returned from the constructor
  103057. * identify as MouseEvents.
  103058. *
  103059. * @constructor
  103060. * @param {String} inType The type of the event to create.
  103061. * @param {Object} [inDict] An optional dictionary of initial event properties.
  103062. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  103063. */
  103064. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  103065. // return value, key, map
  103066. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  103067. // MouseEvent
  103068. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  103069. // DOM Level 3
  103070. "buttons",
  103071. // PointerEvent
  103072. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  103073. // event instance
  103074. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  103075. // MouseEvent
  103076. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  103077. // DOM Level 3
  103078. 0,
  103079. // PointerEvent
  103080. 0,0,0,0,0,0,"",0,!1,
  103081. // event instance
  103082. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  103083. // Scope objects for native events.
  103084. // This exists for ease of testing.
  103085. eventSources:Object.create(null),eventSourceList:[],/**
  103086. * Add a new event source that will generate pointer events.
  103087. *
  103088. * `inSource` must contain an array of event names named `events`, and
  103089. * functions with the names specified in the `events` array.
  103090. * @param {string} name A name for the event source
  103091. * @param {Object} source A new source of platform events.
  103092. */
  103093. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  103094. // call eventsource register
  103095. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  103096. // call eventsource register
  103097. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  103098. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  103099. return!1}},
  103100. // EVENTS
  103101. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  103102. // LISTENER LOGIC
  103103. eventHandler:function(a){
  103104. // This is used to prevent multiple dispatch of pointerevents from
  103105. // platform events. This can happen when two elements in different scopes
  103106. // are set up to create pointer events, which is relevant to Shadow DOM.
  103107. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  103108. // set up event listeners
  103109. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  103110. // remove event listeners
  103111. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  103112. // EVENT CREATION AND TRACKING
  103113. /**
  103114. * Creates a new Event of type `inType`, based on the information in
  103115. * `inEvent`.
  103116. *
  103117. * @param {string} inType A string representing the type of event to create
  103118. * @param {Event} inEvent A platform event with a target
  103119. * @return {Event} A PointerEvent of type `inType`
  103120. */
  103121. makeEvent:function(b,c){
  103122. // relatedTarget must be null if pointer is captured
  103123. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  103124. // make and dispatch an event in one call
  103125. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  103126. * Returns a snapshot of inEvent, with writable properties.
  103127. *
  103128. * @param {Event} inEvent An event that contains properties to copy.
  103129. * @return {Object} An object containing shallow copies of `inEvent`'s
  103130. * properties.
  103131. */
  103132. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  103133. // Work around SVGInstanceElement shadow tree
  103134. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  103135. // This is the behavior implemented by Firefox.
  103136. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  103137. // keep the semantics of preventDefault
  103138. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  103139. // Order of conditions due to document.contains() missing in IE.
  103140. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  103141. // Touch: Do not propagate if node is detached.
  103142. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  103143. * Dispatches the event to its target.
  103144. *
  103145. * @param {Event} inEvent The event to be dispatched.
  103146. * @return {Boolean} True if an event handler returns true, false otherwise.
  103147. */
  103148. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  103149. // is element a shadow host?
  103150. e=this.targetingShadow(f);e;){if(
  103151. // find the the element inside the shadow root
  103152. d=e.elementFromPoint(b,c)){
  103153. // shadowed element may contain a shadow root
  103154. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  103155. // check for older shadows
  103156. e=this.olderShadow(e)}
  103157. // light dom element is the target
  103158. return f}},owner:function(a){
  103159. // walk up until you hit the shadow root or document
  103160. for(var b=a;b.parentNode;)b=b.parentNode;
  103161. // the owner element is expected to be a Document or ShadowRoot
  103162. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  103163. // if x, y is not in this root, fall back to document search
  103164. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  103165. // Only watch scopes that can target find, as these are top-level.
  103166. // Otherwise we can see duplicate additions and removals that add noise.
  103167. //
  103168. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  103169. // a removal without an insertion when a node is redistributed among
  103170. // shadows. Since it all ends up correct in the document, watching only
  103171. // the document will yield the correct mutations to watch.
  103172. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  103173. // register all touch-action = none nodes on document load
  103174. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  103175. // find children with touch-action
  103176. var b=x(a,this.findElements,this);
  103177. // flatten the list
  103178. // make sure the added nodes are accounted for
  103179. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  103180. // handler block for native mouse events
  103181. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  103182. // collide with the global mouse listener
  103183. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  103184. // simulated mouse events will be swallowed near a primary touchend
  103185. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  103186. // Update buttons state after possible out-of-document mouseup.
  103187. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  103188. // Produces wrong state of buttons in Browsers without `buttons` support
  103189. // when a mouse button that was pressed outside the document is released
  103190. // inside and other buttons are still pressed down.
  103191. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  103192. // Support: Firefox <=44 only
  103193. // FF Ubuntu includes the lifted button in the `buttons` property on
  103194. // mouseup.
  103195. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  103196. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  103197. // set touch-action on shadows as well
  103198. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  103199. // remove touch-action from shadow
  103200. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  103201. // simply update scrollType if listeners are already established
  103202. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  103203. // set primary touch if there no pointers, or the only pointer is the mouse
  103204. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  103205. // forward modifier keys
  103206. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  103207. // forward touch preventDefaults
  103208. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  103209. // For single axis scrollers, determines whether the element should emit
  103210. // pointer events or behave as a scroller
  103211. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  103212. // this element is a touch-action: none, should never scroll
  103213. b=!1;else if("XY"===c)
  103214. // this element should always scroll
  103215. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  103216. // if delta in the scroll axis > delta other axis, scroll instead of
  103217. // making events
  103218. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  103219. // In some instances, a touchstart can happen without a touchend. This
  103220. // leaves the pointermap in a broken state.
  103221. // Therefore, on every touchstart, we remove the touches that did not fire a
  103222. // touchend event.
  103223. // To keep state globally consistent, we fire a
  103224. // pointercancel for this "abandoned" touch
  103225. vacuumTouches:function(a){var b=a.touches;
  103226. // pointermap.size should be < tl.length here, as the touchstart has not
  103227. // been processed yet.
  103228. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  103229. // Never remove pointerId == 1, which is mouse.
  103230. // Touch identifiers are 2 smaller than their pointerId, which is the
  103231. // index in pointermap.
  103232. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  103233. // a finger drifted off the screen, ignore it
  103234. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  103235. // recover from retargeting by shadow
  103236. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  103237. // clean up case when finger leaves the screen
  103238. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  103239. // prevent synth mouse events from creating pointer events
  103240. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  103241. // only the primary finger will synth mouse events
  103242. if(this.isPrimaryTouch(c)){
  103243. // remember x/y of last touch
  103244. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  103245. /***/ }),
  103246. /* 36 */
  103247. /***/ (function(module, exports, __webpack_require__) {
  103248. "use strict";
  103249. Object.defineProperty(exports, "__esModule", { value: true });
  103250. var defaultViewer_1 = __webpack_require__(5);
  103251. var mappers_1 = __webpack_require__(1);
  103252. function InitTags(selector) {
  103253. if (selector === void 0) { selector = 'babylon'; }
  103254. var elements = document.querySelectorAll(selector);
  103255. for (var i = 0; i < elements.length; ++i) {
  103256. var element = elements.item(i);
  103257. var configMapper = mappers_1.mapperManager.getMapper('dom');
  103258. var config = configMapper.map(element);
  103259. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  103260. }
  103261. }
  103262. exports.InitTags = InitTags;
  103263. /***/ })
  103264. /******/ ]);
  103265. return BabylonViewer;
  103266. });